Search code examples
iosswiftswift3interface-builderxib

How to bring up a xib as a "pop up" in a ViewController?


I have designed a nice Login box as a xib file in Xcode and when a user taps "Log In" on the landing page on my app, I'd like the Login Box to pop up and let them type in their info.

At the moment though I am having difficulties getting it to show up, as this is my first time working with xibs. Any help would be appreciated. It seems that my IBAction isn't connected because I made a second class, which disconnected the login button from the IBAction. Not sure how to go about fixing that.

Thanks in advance! Using Swift 3 and the latest version on Xcode.

import UIKit

class AuthMainViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    navigationController?.navigationBar.isHidden = true
}
}

class loginClass: UIView {

class func instanceFromNib() -> UIView {
    return UINib(nibName: "LoginView.xib", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
}

@IBAction func loginBtnTapped(_ sender: Any) {
    let loginView = loginClass.instanceFromNib()
    self.addSubview(loginView)
    print("Login got pressed")
}
}

Solution

  • Problem with accepted answer is that in only takes care of the view itself, which is not enough to keep UIKit functioning fully correctly. For having fully functional UIViewController, you should use this:

    //adding UIViewController to another UIViewController:
    addChildViewController(viewController)
    view.addSubview(viewController.view)
    viewController.view.frame = view.bounds
    viewController.didMove(toParentViewController: self)
    
    //removing UIViewController from another UIViewController:
    viewController.willMove(toParentViewController: nil)
    viewController.view.removeFromSuperview()
    viewController.removeFromParentViewController()
    

    Without the other methods you may find malfunctions in many aspect, like:

    • appearance methods
    • rotation methods
    • transition methods
    • responder chain
    • navigation controller, tab bar controller properties

    Reference: https://developer.apple.com/reference/uikit/uiviewcontroller

    "Implementing a Container View Controller"

    Your container view controller must associate a child view controller with itself before adding the child's root view to the view hierarchy