Discoveringmypath
Discoveringmypath

Reputation: 1077

how to segue to storyboard viewcontroller from xib view with swift 3

I'm having the hardest time finding an answer for this.

I have a xib view that is within a scrollview that is within a view controller. In the xib I have a button with an action and I need to segue to a view controller I have in my storyboard. I also would like to be able to use a custom segue.

So far, I have read that I can instantiate the viewcontroller from the storyboard to segue to it. But then I don't know how to present that controller.

thanks for any help...

UPDATE:

this is the code I'm using to perform the segue.

In parent ViewController:

    static var referenceVC: UIViewController?


override func viewDidLoad() {
    super.viewDidLoad()
    print("viewdidload")
    LevelSelectViewController.referenceVC = self

    setupScrollView()
}

code in xib view file

        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sightWordController")

        let parent = LevelSelectViewController.referenceVC!

        let segue = InFromRightCustomSegue(identifier: "test", source: parent, destination: vc)


        segue.perform()

Upvotes: 1

Views: 1317

Answers (1)

TheCodingArt
TheCodingArt

Reputation: 3429

As noted in the comments, Segues are typically confined to storyboard usage as noted in the documentation. You can implement a custom xib view in a storyboard via @IBDesignable like approaches and have you're view load from the xib into the storyboard file/class. This way, you gain the benefits of both worlds. Otherwise, you may want to approach this in another fashion (such as delegates/target-action events, etc).

You may also climb the responder chain and call a segue related to the VC loaded from the storyboard (the segue doesn't necessarily have to be attached to any particular action) via getting a reference to the VC and calling the segue. You can climb the responder chain in a manner such as the example code below:

protocol ChildViewControllerContainer {
    var parentViewController: UIViewController? { get }
}


protocol ViewControllerTraversable {
    func viewController<T: UIViewController>() -> T?
}

extension UIView: ViewControllerTraversable {

    func viewController<T: UIViewController>() -> T? {
        var responder = next

        while let currentResponder = responder {
            guard responder is T else {
                responder = currentResponder.next
                continue
            }

            break
        }

        return responder as? T
    }
}

extension UITableViewCell: ChildViewControllerContainer {
    weak var parentViewController: UIViewController? {
        return viewController() as UIViewController?
    }
}

Upvotes: 3

Related Questions