Loading ViewController from xib file

前端 未结 10 2394
我在风中等你
我在风中等你 2020-12-08 02:33

I had a MyViewController.swift and a MyViewController.xib presenting the layout of MyViewController.

I tried different methods to load this

相关标签:
10条回答
  • 2020-12-08 02:53

    I removed File owner’s class name and set that to the class name of first view. And then I had to set outlets to the components which I’m going to use.

    Then I loaded that view class like

    let myViewController = Bundle.main.loadNibNamed("MyViewController", owner: self, options: nil)?.first as! MyViewController
    view.addSubview(myViewController)
    
    0 讨论(0)
  • 2020-12-08 02:55

    Updated for Swift 5

            let myVC = Bundle.main.loadNibNamed("MyViewController", owner: self, options: nil)![0] as? MyViewController
    
    0 讨论(0)
  • 2020-12-08 02:58
    extension UIViewController {
        static func loadFromNib() -> Self {
            func instantiateFromNib<T: UIViewController>() -> T {
                return T.init(nibName: String(describing: T.self), bundle: nil)
            }
    
            return instantiateFromNib()
        }
    }
    

    Use it as the following:-

    let testVC = TestVC.loadFromNib()
    
    0 讨论(0)
  • 2020-12-08 03:03

    I had the same problem. The automatically generated xib had a UIView in it. You have to delete the view, add new view controller to the xib, set the view controller class to the one you want and then connect the outlets. After all of this you can use the codes provided above to get an instance of this view controller, like this:

    if let menuVC = Bundle.main.loadNibNamed("MenuViewController", owner: nil, options: nil)?.first as? MenuViewController {
                menuVC.profileType = profileType
                vc.present(menuVC, animated: true, completion: nil)
            }
    
    0 讨论(0)
提交回复
热议问题