Perform unwind segue programmatically

2019-08-15 04:49发布

问题:

Currently I have the following storyboard:

UITableViewController -> Segue -> UINavigationController -> Relationship -> UITableViewController

In the last UITableViewController I added a back button with the code below:

navigationItem.setLeftBarButtonItem(UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "unwind"), animated: true)

let attributes = [NSFontAttributeName: UIFont.fontAwesomeOfSize(30), NSForegroundColorAttributeName: Constants.InterfaceColors.firstHighlightColor] as Dictionary!
let unwindNavigationItem = navigationItem.leftBarButtonItem! as UIBarButtonItem

unwindNavigationItem.setTitleTextAttributes(attributes, forState: .Normal)
unwindNavigationItem.title = String.fontAwesomeIconWithName(FontAwesome.AngleLeft)

As far as I read I have to connect the File's owner to the exit in the storyboard. I found out, that this is only possible if you have an action in your controller code like the one below.

@IBAction func unwindToWeekOverview(segue: UIStoryboardSegue) {
        NSLog("unwind to week overview")
        dismissViewControllerAnimated(true, completion: nil)
    }

Since I don't now how to directly connect the action of a button to my unwind action I added the unwind function.

func unwind() {
        performSegueWithIdentifier("UnwindToWeekOverview", sender: self)
    }

When I now click the back button, the unwind function is called, but not the segue. What am I missing?

回答1:

Have a look at this link. It is by MIKE WOELMER and he explains it very clearly.

https://spin.atomicobject.com/2014/10/25/ios-unwind-segues/

So first of all, you need to create an IBAction in a destination view controller, something like this:

@IBAction func goBack(segue: UIStoryboardSegue) {

    print("go back")

Then you just need to connect (control drag) from your button to Exit outlet. In the pop up you will see the function added previously, just select it and it should work.