How to add right button in the navigation bar?
Solution 1
The Swift version of Vahan Babayan's answer, as you seem to use this language, is:
let rightButtonItem = UIBarButtonItem.init(
title: "Title",
style: .Done,
target: self,
action: "rightButtonAction:"
)
self.navigationItem.rightBarButtonItem = rightButtonItem
The following method will be called on self:
func rightButtonAction(sender: UIBarButtonItem)
Note that all this can be set graphically using a Storyboard, by dragging a Bar Button Item to your Navigation Item and right-clicking to set a target-action.
A small update since Swift 3 and 4 are out: the compiler can now check selector names, preventing typos when setting up target-action programatically. So one should really use:
let rightButtonItem = UIBarButtonItem.init(
title: "Title",
style: .Done,
target: self,
action: #selector(rightButtonAction(sender:))
)
Solution 2
You can add the following code to your B controller's viewDidLoad
method.
UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Title"
style:UIBarButtonItemStyleDone
target:self
action:@selector(rightButtonAction:)];
self.navigationItem.rightBarButtonItem = rightButtonItem;
Solution 3
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]initWithTitle:@"Right Button" style:UIBarButtonItemStyleDone target:self action:@selector(rightBtnClick)];
self.navigationItem.rightBarButtonItem = rightBtn;
}
-(void)rightBtnClick{
// code for right Button
}
user2262304
Updated on August 17, 2020Comments
-
user2262304 almost 4 years
I have a question to add a right button in navigation bar..
I have two views: View A and View B
I add a navigation bar to view A, after I used
self.navigationController!.pushViewController
to show view B.That show a back button in the left of navigation bar of view B automatic, it is good. but now I want to add a button in the right of navigation bar of view B.. I have tried some answers, but it doesn't work... I have tried answers likes : 1) https://www.hackingwithswift.com/example-code/uikit/how-to-add-a-bar-button-to-a-navigation-bar 2)http://blog.apoorvmote.com/add-multiple-bar-button-item-navigation-bar/?lang=fr
Could you help me, thank you !
-
user2262304 about 8 yearsThank you for your answer, I have fund the answer to ` let rightBtn = UIBarButtonItem(title: "Send", style: .Plain, target: self, action: "send:") self.navigationItem.setRightBarButtonItem(rightBtn, animated: true)` I know I can use XIB to do that, but I do not why the position of the right button is not the same with by XIB, so I use code to do this