简体   繁体   中英

Can't get a back button on my view controller in Swift

Here's what's going on:

I have a Navigation Controller with A-TableViewController set as root view controller. Once I click on a cell in A, it'll take me to B-ViewController. The navigation controller has an identifier "MessagesViewController". Here's my code thus far in A-TableViewController:

func tableView (tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let sb = UIStoryboard(name: "Main", bundle: nil)
    let messagesVC = sb.instantiateViewControllerWithIdentifier("MessagesViewController") as! MessagesViewController
    //Some code here
    //This has a back button, but nothing else
    self.navigationController?.pushViewController(messagesVC, animated: true)
    //This has no back button, but everything else that I intended works
    self.navigationController?.presentViewController(messagesVC, animated: true, completion: nil)

I want to be able to go back to A-TableViewController with everything working. Is it the way I'm pushing/presenting the view controller that's messing it up? Anyone have any clue why I've been stuck on this for the past 3 days?

You get built in back button when you push a view on to a navigation view. The presentViewController is modally displaying your view. What I've done in the past is add my own back button to the view and present it. Then when you press it you call dismissViewController.

You can use the prepareForSegue method to pass data, something like this:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if segue.identifier == "messageSegue" {
        let vc:  B-ViewController = segue.destinationViewController as!  B-ViewController
        //then set properties of your new viewController like this
        vc.property = dataToPass
    }
}

If you are indeed using a navigation controller, than your problem should be quite simple. Create an @IBAction, and in it, call popToRootViewControllerAnimated, like so:

 @IBAction func rootButton(sender: UIButton) {
    navigationController?.popToRootViewControllerAnimated(true) // or false :)

}

After Presenting your B-ViewController Try this in viewDidLoad:

let btnBack = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(dismissVC))
    btnBack.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .normal)
    navigationItem.setLeftBarButton(btnBack, animated: true)

@objc func dismissVC() {
    self.dismiss(animated: true, completion: nil)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM