A.s.ALI
A.s.ALI

Reputation: 2082

Loading a ViewController from nib file owner

I have a design made in nib and in round about all ViewControllers I am loading that nib design.

Now as that was common footer so I managed to used it in the footer of all other view controllers.

Now what I want : I want that whenever User click on a footer it must start a new View Controller that will show what you can say "About us " view controller.

What I am doing:

// ON CLICK OF FOOTER I AM DOING 
 let mAboutUs = self.storyboard?.instantiateViewController(withIdentifier: "idAboutUs") as! AboutUs
    mAboutUs.modalPresentationStyle = .fullScreen
    self.present(mAboutUs, animated: true) {

    }

but I am getting following error

Value of type 'FooterView' has no member 'storyboard'

My Understanding: I think from nib file we can not start a new ViewController, But I really do not want to do this thing in all other View controllers in which I added this nib (FooterView) as my footer view at bottom of each view controller.

Please help me!!!!

Upvotes: 0

Views: 691

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100541

A UIView subclass doesn't contain a storyboard property it's for a vc subclass , You need

let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "idAboutUs") as! AboutUs

if you want to present a vc from inisde the view FooterView then add a delegate like

weak var delegate:VCName?

When you create an instance

let ins = FooterView() // or from storyboard 
ins.delegate = self

Then use

delegate?.present(mAboutUs, animated: true)

inside the view's class


You can use a delegate that all vcs conforms to but the easiest is to add this extension

extension UIViewController {
    func topMostViewController() -> UIViewController {

        if let presented = self.presentedViewController {
            return presented.topMostViewController()
        }

        if let navigation = self as? UINavigationController {
            return navigation.visibleViewController?.topMostViewController() ?? navigation
        }

        if let tab = self as? UITabBarController {
            return tab.selectedViewController?.topMostViewController() ?? tab
        }

        return self
    }
}

Then

 guard let currentVC =  (UIApplication.shared.delegate as! AppDelegate).window?.rootViewController.topMostViewController() else { return } 
 currentVC.present(mAboutUs, animated: true)

Upvotes: 2

CristiCh
CristiCh

Reputation: 11774

Your code should look similar to this:

let vc = UIStoryboard(name: "<Name of the storyboard that contains the About Us VC>", bundle: nil).instantiateViewController(withIdentifier: "idAboutUs") as! AboutUs

self.present(vc, animated: true) {

    }

Upvotes: 0

Related Questions