patrickhuang94
patrickhuang94

Reputation: 2115

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?

Upvotes: 0

Views: 2323

Answers (4)

Twinkle
Twinkle

Reputation: 21

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)
}

Upvotes: 1

dannybess
dannybess

Reputation: 599

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 :)

}

Upvotes: 0

Oscar
Oscar

Reputation: 1035

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.

Upvotes: 1

Rachel Harvey
Rachel Harvey

Reputation: 1789

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
    }
}

Upvotes: 0

Related Questions