2
votes

My goal is to add a cancel bar item on a navigation bar. The scenario is a user presses the button then it will segue modally to another UIView Controller and there will be a cancel button. The cancel button will bring the use back to the first screen

Example

enter image description here

what I did currently is drag a navigation bar onto UIViewController, it works but when I try to drag bar item onto the navigation bar, it doesn't work. What am I missing right now?

3
i think for the above screen you don not need navigation bar. Just place a button and implement the actioniCoder
what part is "doesn't work"? you can treat it as a normal button and create property for itTj3n
were you able to find the solution?Bista

3 Answers

3
votes

Add UIBarButtonItem in navigation bar programmatically

let btnCancel = UIButton()
btnCancel.setImage(UIImage(named: "crossbuttonimagename"), forState: .Normal)
btnCancel.frame = CGRectMake(0, 0, 25, 25)
btnCancel.addTarget(self, action: Selector("youraction"), forControlEvents: .TouchUpInside)

//Set Left Bar Button item
let leftBarButton = UIBarButtonItem()
leftBarButton.customView = btnCancel
self.navigationItem.leftBarButtonItem = leftBarButton
1
votes
  1. Embed your Second View controller into a Navigation Controller.
  2. Present modally this Navigation Controller.
  3. Drag & Drop an UIBarButton Item (X button) to the Navigation Bar in the Second View Controller.
  4. Create an action to go back to First View Controller.

    @IBAction func actionDismiss(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
  5. Assign this action to the Cancel Button.

0
votes
  1. Select the segue which leads to the problematic view controller
  2. Set that to PUSH segue
  3. Again unselect the PUSH segue and now accepted SHOW segue

After these step you can add right bar button item using storyboard.