Search code examples
iosswiftiphonexcode10swift4.2

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!!!!


Solution

  • 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)