问题
I have a storyboard that looks like the image shown. The single navigation controller manages my drill down navigation adds a Back button to all of the views 1,2,3 and 4 as I drill down. What I would like to do, is add an additional button on the "back" nav bar on the right for each of the 3 tab views (2,3 and 4) Can this be done in Swift? Can anyone help? I cannot add it using the storyboard as the button just seems to disappear on the storyboard and does not get displayed when I run the app.
回答1:
You don't want to add another back button; you want to add a right bar button item. You can do this either in code or in the storyboard.
In code, you need to do something like:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Some Title", style: .Plain, target: self, action: <your-selector>)
where the target and action point to some method on your view controller (or on another object, if that's how you've set it up).
In the storyboard,
- If the view controllers don't already have one, drag a
UINavigationItemto each view controller. - Drag a
UIBarButtonItemonto the right side of each view controller's navigation bar.
- Configure the title or image of the button.
- Control-drag from the right bar button item to the view controller that it's in and select the
IBActionmethod that you want to be fired when the button is tapped.
回答2:
Try dragging a Bar Button Item, not UI button. and you can set the titles of the buttons in view did load of each controller or even create the button in code. Here is how to do that
override func viewDidLoad() {
super.viewDidLoad()
let barButton = UIBarButtonItem(title: "VC1 bar button", style: UIBarButtonItemStyle.Plain, target: self, action: "The action function name")
self.navigationItem.rightBarButtonItem = barButton
}
回答3:
Put this in your viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Custom, target: self, action: "*add a func saying what you want the button to do*")
Example:
func save() {
UIImageWriteToSavedPhotosAlbum(imageView.image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
}
So in this case, I would say:
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Custom, target: self, action: "save")
I hope this helps!
Note: You won't be able to see it in the storyboard, only when you run the app
回答4:
I found an easy way to do that
let barButton = UIBarButtonItem(image: UIImage(named: "YourImage"), style: .plain, target: self, action: #selector(yourClass.yourFunction(_:)))
self.navigationController?.topViewController?.navigationItem.rightBarButtonItem = barButton
Add this code and all the view controllers you want to add a right button besides the back button.
I hope that this code help you!
来源:https://stackoverflow.com/questions/33204457/add-additional-button-next-to-back-button-on-tab-embedded-in-navigation-controll