I have a UIViewController with a UITableView in it, and also added a UINavigationBar.
How can I add and "edit" button and a "+" button in that bar programmatically?
(I have tried using IB, but the title is always replaced, and not other items are added)
I am not using a UINavigationController. is my UIViewController standing alone.
This is what I have tried without success:
UIBarButtonItem *barButton =
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonItemStyleBordered
target:nil
action:nil];
UINavigationItem *editItem = [[UINavigationItem alloc] initWithTitle:#"Title"];
[editItem setLeftBarButtonItem:barButton animated:YES];
[navigationBar setItems:[NSArray arrayWithObject:editItem] animated:YES];
Your UIViewController has a navigationItem property. You can set the left and right bar button items with self.navigationItem.leftBarButtonItem = ... and self.navigationItem.rightBarButtonItem = ...
Edit:
OK, I assume you have a reference to your UINavigationBar?
Then I guess you'd add a single UINavigationItem to it:
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:#"A Title"];
theNavigationBar.items = [NSArray arrayWithObject:item];
[item release]; // or keep this as an instance variable
and then set that item's left and right buttons:
theNavigationBar.topItem.leftBarButtonItem = ...;
theNavigationBar.topItem.rightBarButtonItem = ...;
I haven't tried this, but I think it should work.
UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(theEditMethod:)];
[viewController.navigationItem setLeftBarButtonItem:leftBarButton animated:NO];
[leftBarButton release];
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(theAddMethod:)];
[viewController.navigationItem setLeftBarButtonItem:rightBarButton animated:NO];
[rightBarButton release];
Yo do not need to add UINavigationItem to the UINavigationBar. Yo can do as this example:
NSString *backButtonTittle=[NSString stringWithFormat:#"< %#",NSLocalizedString(#"backButton", nil)];
UIBarButtonItem *backCreateAccountNavBarItem=[[UIBarButtonItem alloc]initWithTitle:backButtonTittle style:UIBarButtonItemStylePlain target:self action:#selector(goToBackStep)];
self.createAccountNavBar.topItem.leftBarButtonItem=backCreateAccountNavBarItem;
Just use your viewController's navigationItem property.
like this:
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:#selector(updateContent)];
Navigation Bar items/buttons with actions on Swift 4.2, ios 11, XCode 10
1) With Storyboard go to Editor > Embed In > Navigation Bar
2) In AppDelegate > didFinishLaunchingWithOptions:
UINavigationBar.appearance().barTintColor = UIColor(hexString: "1C9B90")
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
3) On viewDidLoad for your viewcontroller, create buttons and add to Navigation Bar:
self.navigationController?.navigationBar.topItem?.title = "Title"
self.navigationController?.isNavigationBarHidden = false
//QR Code button
let qrCodeScanButton = UIButton(type: .custom)
qrCodeScanButton.setImage(UIImage(named: "camera"), for: .normal)
qrCodeScanButton.addTarget(self, action: #selector(self.searchWithQRCode), for: .touchUpInside)
let qrCodeScanButtonItem = UIBarButtonItem(customView: qrCodeScanButton)
///LogOut button
let logoutButton = UIButton(type: .custom)
logoutButton.setImage(UIImage(named: "logOut"), for: .normal)
logoutButton.addTarget(self, action: #selector(self.logOut), for: .touchUpInside)
let logoutButtonItem = UIBarButtonItem(customView: logoutButton)
self.navigationController?.navigationBar.topItem?.setRightBarButtonItems([logoutButtonItem, qrCodeScanButtonItem], animated: true)
4) Actions for buttons:
#objc func logout(){
///present your Login VC
}
#objc func qrCodeScanButton(){
///present your Login VC
}
5) Build and Run
PS. Keep in mind these two differences.
isNavigationBarHidden: A Boolean value that indicates whether the navigation bar is hidden.
self.navigationController?.isNavigationBarHidden
navigationBar.isHidden: The navigation bar managed by the navigation controller.
self.navigationController?.navigationBar.isHidden
Related
I can implement navigation bar and add left bar button, but before left button have space, please ask how to remove this space in ios 7.
use this it will work i have used it and works fine on iOS 7 also
UIBarButtonItem *homeButton = [[UIBarButtonItem alloc] initWithCustomView:segmentView];
UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
target:nil action:nil];
negativeSpacer.width = -6;// it was -6 in iOS 6 you can set this as per your preference
[self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:negativeSpacer,homeButton, nil] animated:NO];
You could use a system .fixedSpace UIBarButtonItem.
Here is a swift version producing the expected result (iOS 10+):
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
negativeSpacer.width = -20 // working on iOS 10.
let barButton = UIBarButtonItem(title: "<# title #>", style: .plain, target: <# target #> , action: #selector(<# action #>))
navigationItem.leftBarButtonItems = [negativeSpacer, barButton]
Another idea is to add a UIButton to the UINavigationController.view directly.
We can add customize left bar button of navigation bar, but before left button have space. I fix this issue as following,
Calling:
// MyViewController.m
- (void)viewDidLoad {
UIBarButtonItem *bbBack = [Utilities overrideBackBarButtonItemWithTarget:self action:#selector(btnBackTapped:)];
}
- (void)btnBackTapped:(id)sender {
//Custom navigation back bar button item
}
Add this class method to your Utilities class or any common class for your project,
Implementation:
// Utilities.h
#interface Utilities : NSObject
#pragma mark - back bar button item
+(UIBarButtonItem*)overrideBackBarButtonItemWithTarget:(nullable id)target action:(nullable SEL)action;
#end
// Utilities.m
#implementation Utilities
+(UIBarButtonItem*)overrideBackBarButtonItemWithTarget:(nullable id)target action:(nullable SEL)action {
// back button
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65 , 44)];
[btn setImage:[UIImage imageNamed:#"back"] forState:UIControlStateNormal];
btn.imageEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 15);//move image to the right
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barbuttonBack = [[UIBarButtonItem alloc] initWithCustomView:btn];
//navigation spacer
UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
spacer.width = -15;// it was -6 in iOS 6 you can set this as per your preference
//set leftBarButtonItems
UIViewController *_self = (UIViewController*)target;
[_self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:spacer,barbuttonBack, nil] animated:NO];
return barbuttonBack;
}
#end
Back image:
back.png
Actually i am placing a bar button on right side of navigation bar, it's not working. But when i use it as left bar button item, it's working fine. I am using ios5.
It was also not working when i have both button left and right bar button. Then i set the frame for both, then these are working. But when i have only one button on right side, it's not working.
UIButton *but1 = [UIButton buttonWithType:UIButtonTypeCustom];//customising map button.
but1.frame = CGRectMake(270,0,50,40);
[but1 addTarget:self action:#selector(clicked) forControlEvents:UIControlEventTouchUpInside];//on cilcking an map button clicked method is called.
buttonRight = [[UIBarButtonItem alloc]initWithCustomView:but1];//setting map button on Navigation bar.
self.navigationItem.rightBarButtonItem = buttonRight;//setting button on the Right of navigation bar.
how to trace out this error?
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle: #"edit" style: UIBarButtonItemStyleBordered target: self action: #selector(edit_details)];
self.navigationItem.rightBarButtonItem = addButton;
UIToolbar* toolbar = [[UIToolbar alloc]
initWithFrame:CGRectMake(0, 0, 50, 45)];
[toolbar setBarStyle: UIBarStyleBlackOpaque];
// create an array for the buttons
NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:0];
// create a standard BarButtonItem
UIBarButtonItem *SettingsBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:#"icon_setting.png"] style:UIBarButtonItemStylePlain
target:self
action:#selector(ActionMethod:)];
[buttons addObject:SettingsBtn];
[SettingsBtn release];
// put the buttons in the toolbar and release them
[toolbar setItems:buttons animated:NO];
[buttons release];
// place the toolbar into the navigation bar
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithCustomView:toolbar]autorelease];
[toolbar release];
For Swift 4.2 code:
In the View did load function
let addButton = UIBarButtonItem(title: "edit", style: .plain, target: self, action: #selector(edit))
navigationItem.rightBarButtonItem = addButton
Function definition goes here:
#objc func edit() {
// Body definition
}
I have a UINavigationController that has its left and right button properties set. Instead of having the title in the middle, I want to put a button there. I'm not sure how I can achieve this.
CODE:
UIBarButtonItem* titleButton = [[UIBarButtonItem alloc]
initWithTitle:symbol
style:UIBarButtonItemStyleBordered
target:self
action:#selector(addToWatchlistButtonClicked:)];
self.navigationItem.titleView = titleButton;
Use titleView property of UINavigationItem.
self.navigationItem.titleView = button;
For an application I'm developing, I need to display a custom back button in a navigation bar. I have the button asset as a PNG image, and I'm writing this code:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(0, 0, 79, 29.0);
[backButton setImage:[UIImage imageNamed:#"button_back.png"] forState:UIControlStateNormal];
self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
}
When I push this view controller, the custom button does not show up, and instead I get the standard back button with the title of this view controller inside.
Things I already tried:
Doubled check that the button backButton is created properly, by adding it to the view hierarchy. It displays properly.
In the same method, changed the title property of the navigationItem and confirmed that it changes (as expected) the content of my back button.
Can anyone spot what I'm doing wrong? Did anyone succeed in using a custom image as the back button on with a UINavigationController?
Starting with iOS 5, this is simple:
[[UIBarButtonItem appearance]
setBackButtonBackgroundImage:[UIImage imageNamed:#"back_button.png"]
forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
You can place that in your app delegate and it will set the background image to all back buttons in the app (for that control state and bar metrics, of course).
I'm reposting my solution from https://stackoverflow.com/a/16831482/171933:
I create a simple category on UIViewController:
UIViewController+ImageBackButton.h
#import <UIKit/UIKit.h>
#interface UIViewController (ImageBackButton)
- (void)setUpImageBackButton;
#end
UIViewController+ImageBackButton.m
#import "UIViewController+ImageBackButton.h"
#implementation UIViewController (ImageBackButton)
- (void)setUpImageBackButton
{
UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 34, 26)];
[backButton setBackgroundImage:[UIImage imageNamed:#"back_arrow.png"] forState:UIControlStateNormal];
UIBarButtonItem *barBackButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
[backButton addTarget:self action:#selector(popCurrentViewController) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = barBackButtonItem;
self.navigationItem.hidesBackButton = YES;
}
- (void)popCurrentViewController
{
[self.navigationController popViewControllerAnimated:YES];
}
#end
Now all you have to do is #import UIViewController+ImageBackButton.h in either all of your view controllers or in a custom base view controller class that your other view controllers inherit from and implement the viewWillAppear: method:
- (void)viewWillAppear:(BOOL)animated
{
[self setUpImageBackButton];
}
That's all. Now you have an image back button everywhere. Without a border. Enjoy!
The backBarButtonItem property works as intended, but it will always add its standard button shape and color based on the navigation bar tint color.
You can customize the text, but not replace the image.
One workaround, as Andrew Pouliot suggested, is to use leftBarButtonItem instead, but I stuck to the standard button instead.
Isn't the simplest solution just to design it from your storyboard with whatever image or colors you want, and just drag a new action to your controller?
Swift Code
#IBAction func backButton(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
Confusingly backBarButtonItem is not what you're looking for.
It just controls the title on the back button for the next view controller. What you want is to set the leftBarButtonItem to your custom back button.
Johannes Fahrenkrug's Answer works, but the back image would appear at a very wired position.
Here I found a better way to position the image at the right place:
Make Sure You Have a back image with size 24x24(#1x) , I call it backImage
Execute the following code when your app Launch
UINavigationBar.appearance().barTintColor = nil
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: .Default)
See this answer here: How to create backBarButtomItem with custom view for a UINavigationController
You just need to set the backBarButtonItem property on the navigationController before pushing the viewController. Setting the backBarButtonItem property in the viewController's viewDidLoad method (for example) doesn't work.
I do not think that ViewController itself should know anything about its back button
According to OOP this is the responsibility of containerViewController in which your view controller is inserted, for example UINavigationController.
Subclass your NavigationController and overload in it superClass method like this:
#implementation STONavigationController
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
[super pushViewController:viewController animated:animated];
if ([self.viewControllers indexOfObject:viewController] != NSNotFound &&
[self.viewControllers indexOfObject:viewController] > 0){
UIImage *img = [UIImage imageNamed:#"back-1"];
UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, img.size.width * 2, img.size.height * 2)];
[backButton setBackgroundImage:img forState:UIControlStateNormal];
UIBarButtonItem *barBackButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
[backButton addTarget:self action:#selector(popCurrentViewController) forControlEvents:UIControlEventTouchUpInside];
viewController.navigationItem.leftBarButtonItem = barBackButtonItem;
viewController.navigationItem.hidesBackButton = YES;
}
}
- (void)popCurrentViewController
{
[self popViewControllerAnimated:YES];
}
#end
Simply create a UIBarButtonItem instead of an embedded UIButton in UIBarButtonItem. Works fine!
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"button_back.png"] style:UIBarButtonItemStyleBordered target:nil action:nil];
self.navigationItem.backBarButtonItem = backButton;
As #pgb suggested you can use leftBarButtonItem instead of back button item. And to remove the default back button item set it to nil like follows;
navigationController?.navigationBar.backIndicatorImage = nil
navigationController?.navigationBar.backIndicatorTransitionMaskImage = nil
let button = UIButton.init(type: .custom)
button.imageView?.contentMode = UIViewContentMode.scaleAspectFit
button.setImage(UIImage.init(named: "top_back"), for: UIControlState.normal)
button.frame = CGRect.init(x: 0, y: 0, width: 75, height: 50)
button.addTarget(self, action: #selector(handleBackButton), for: .touchUpInside)
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton
I am trying to add a refresh button to the top bar of a navigation controller with no success.
Here is the header:
#interface PropertyViewController : UINavigationController {
}
Here is how I am trying to add it:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:#"Show" style:UIBarButtonItemStylePlain
target:self action:#selector(refreshPropertyList:)];
self.navigationItem.rightBarButtonItem = anotherButton;
}
return self;
}
Try doing it in viewDidLoad. Generally you should defer anything you can until that point anyway, when a UIViewController is inited it still might be quite a while before it displays, no point in doing work early and tying up memory.
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:#"Show" style:UIBarButtonItemStylePlain target:self action:#selector(refreshPropertyList:)];
self.navigationItem.rightBarButtonItem = anotherButton;
// exclude the following in ARC projects...
[anotherButton release];
}
As to why it isn't working currently, I can't say with 100% certainty without seeing more code, but a lot of stuff happens between init and the view loading, and you may be doing something that causes the navigationItem to reset in between.
Try adding the button to the navigationItem of the view controller that is going to be pushed onto this PropertyViewController class you have created.
That is:
MainViewController *vc = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[infoButton addTarget:self action:#selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
vc.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:infoButton] autorelease];
PropertyViewController *navController = [[PropertyViewController alloc] initWithRootViewController:vc];
Now, this infoButton that has been created programatically will show up in the navigation bar. The idea is that the navigation controller picks up its display information (title, buttons, etc) from the UIViewController that it is about to display. You don't actually add buttons and such directly to the UINavigationController.
It seems that some people (like me) may come here looking for how to add a navigation bar button in the Interface Builder. The answer below shows how to do it.
Add a Navigation Controller to your Storyboard
Select your View Controller and then in the Xcode menu choose Editor > Embed In > Navigation Controller.
Alternatively, you could add a UINavigationBar from the Object Library.
Add a Bar Button Item
Drag a UIBarButtonItem from the Object Library to the top navigation bar.
It should look like this:
Set the Attributes
You could double-click "Item" to change the text to something like "Refresh", but there is an actual icon for Refresh that you can use. Just select the Attributes Inspector for the UIBarButtonItem and for System Item choose Refresh.
That will give you the default Refresh icon.
Add an IB Action
Control drag from the UIBarButtonItem to the View Controller to add an #IBAction.
class ViewController: UIViewController {
#IBAction func refreshBarButtonItemTap(sender: UIBarButtonItem) {
print("How refreshing!")
}
}
That's it.
There is a default system button for "Refresh":
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self action:#selector(refreshClicked:)] autorelease];
self.navigationItem.rightBarButtonItem = refreshButton;
}
- (IBAction)refreshClicked:(id)sender {
}
You Can use this:
Objective-C
UIBarButtonItem *rightSideOptionButton = [[UIBarButtonItem alloc] initWithTitle:#"Right" style:UIBarButtonItemStylePlain target:self action:#selector(rightSideOptionButtonClicked:)];
self.navigationItem.rightBarButtonItem = rightSideOptionButton;
Swift
let rightSideOptionButton = UIBarButtonItem()
rightSideOptionButton.title = "Right"
self.navigationItem.rightBarButtonItem = rightSideOptionButton
-(void) viewWillAppear:(BOOL)animated
{
UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
[btnRight setFrame:CGRectMake(0, 0, 30, 44)];
[btnRight setImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
[btnRight addTarget:self action:#selector(saveData) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barBtnRight = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
[barBtnRight setTintColor:[UIColor whiteColor]];
[[[self tabBarController] navigationItem] setRightBarButtonItem:barBtnRight];
}
For swift 2 :
self.title = "Your Title"
var homeButton : UIBarButtonItem = UIBarButtonItem(title: "LeftButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("yourMethod"))
var logButton : UIBarButtonItem = UIBarButtonItem(title: "RigthButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("yourMethod"))
self.navigationItem.leftBarButtonItem = homeButton
self.navigationItem.rightBarButtonItem = logButton
You can try
self.navigationBar.topItem.rightBarButtonItem = anotherButton;
Here is the solution in Swift (set options as needed):
var optionButton = UIBarButtonItem()
optionButton.title = "Settings"
//optionButton.action = something (put your action here)
self.navigationItem.rightBarButtonItem = optionButton
Why are you subclasses UINavigationController? There is no need to subclass it if all you need to do is add a button to it.
Set up a hierarchy with a UINavigationController at the top, and then in your root view controller's viewDidLoad: method: set up the button and attach it to the navigation item by calling
[[self navigationItem] setRightBarButtonItem:myBarButtonItem];
Swift 4 :
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "tap me", style: .plain, target: self, action: #selector(onButtonTap))
}
#objc func onButtonTap() {
print("you tapped me !?")
}
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 110, 50)];
view.backgroundColor = [UIColor clearColor];
UIButton *settingsButton = [UIButton buttonWithType:UIButtonTypeCustom];
[settingsButton setImage:[UIImage imageNamed:#"settings_icon_png.png"] forState:UIControlStateNormal];
[settingsButton addTarget:self action:#selector(logOutClicked) forControlEvents:UIControlEventTouchUpInside];
[settingsButton setFrame:CGRectMake(40,5,32,32)];
[view addSubview:settingsButton];
UIButton *filterButton = [UIButton buttonWithType:UIButtonTypeCustom];
[filterButton setImage:[UIImage imageNamed:#"filter.png"] forState:UIControlStateNormal];
[filterButton addTarget:self action:#selector(openActionSheet) forControlEvents:UIControlEventTouchUpInside];
[filterButton setFrame:CGRectMake(80,5,32,32)];
[view addSubview:filterButton];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
Try this.It work for me.
Navigation bar and also added background image to right button.
UIBarButtonItem *Savebtn=[[UIBarButtonItem alloc]initWithImage:[[UIImage
imageNamed:#"bt_save.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain target:self action:#selector(SaveButtonClicked)];
self.navigationItem.rightBarButtonItem=Savebtn;
UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(add:)];
self.navigationItem.rightBarButtonItem = rightBarButtonItem;
- (void)viewWillAppear:(BOOL)animated
{
[self setDetailViewNavigationBar];
}
-(void)setDetailViewNavigationBar
{
self.navigationController.navigationBar.tintColor = [UIColor purpleColor];
[self setNavigationBarRightButton];
[self setNavigationBarBackButton];
}
-(void)setNavigationBarBackButton// using custom button
{
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:#" Back " style:UIBarButtonItemStylePlain target:self action:#selector(onClickLeftButton:)];
self.navigationItem.leftBarButtonItem = leftButton;
}
- (void)onClickLeftButton:(id)sender
{
NSLog(#"onClickLeftButton");
}
-(void)setNavigationBarRightButton
{
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:#"Show" style:UIBarButtonItemStylePlain target:self action:#selector(onClickrighttButton:)];
self.navigationItem.rightBarButtonItem = anotherButton;
}
- (void)onClickrighttButton:(id)sender
{
NSLog(#"onClickrighttButton");
}
self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:#selector(refreshData)];
}
-(void)refreshData{
progressHud= [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
[progressHud setLabelText:#"拼命加载中..."];
[self loadNetwork];
}
You should add your barButtonItem in - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated method.
Just copy and paste this Objective-C code.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self addRightBarButtonItem];
}
- (void) addRightBarButtonItem {
UIButton *btnAddContact = [UIButton buttonWithType:UIButtonTypeContactAdd];
[btnAddContact addTarget:self action:#selector(addCustomerPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btnAddContact];
self.navigationItem.rightBarButtonItem = barButton;
}
#pragma mark - UIButton
- (IBAction)addCustomerPressed:(id)sender {
// Your right button pressed event
}
This issue can occur if we delete the view controller or try to add new view controller inside the interface builder(main.storyboard). To fix this issue, it requires to add "Navigation Item" inside new view controller. Sometimes it happens that we create new view controller screen and it does not connect to "Navigation Item" automatically.
Go to the main.storyboard.
Select that new view Controller.
Go to the document outline.
Check view Controller contents.
If new view controller does not have a Navigation item then, copy Navigation item from previous View Controller and paste it into the new view controller.
save and clean the project.
Also you are able to add multiple buttons using rightBarButtonItems
-(void)viewDidLoad{
UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:#"button 1" style:UIBarButtonItemStylePlain target:self action:#selector(YOUR_METHOD1:)];
UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithTitle:#"button 2" style:UIBarButtonItemStylePlain target:self action:#selector(YOUR_METHOD2:)];
self.navigationItem.rightBarButtonItems = #[button1, button2];
}
#Artilheiro : If its a navigationbased project, u can create BaseViewController. All other view will inherit this BaseView. In BaseView u can define generic methods to add right button or to change left button text.
ex:
#interface BaseController : UIViewController {
}
- (void) setBackButtonCaption:(NSString *)caption;
(void) setRightButtonCaption:(NSString *)caption selectot:(SEL )selector;
#end
// In BaseView.M
(void) setBackButtonCaption:(NSString *)caption
{
UIBarButtonItem *backButton =[[UIBarButtonItem alloc] init];
backButton.title= caption;
self.navigationItem.backBarButtonItem = backButton;
[backButton release];
}
- (void) setRightButtonCaption:(NSString *)caption selectot:(SEL )selector
{
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] init];
rightButton.title = caption;
rightButton.target= self;
[rightButton setAction:selector];
self.navigationItem.rightBarButtonItem= rightButton;
[rightButton release];
}
And now in any custom view, implement this base view call the methods:
#interface LoginView : BaseController {
In some method call base method as:
SEL sel= #selector(switchToForgotPIN);
[super setRightButtonCaption:#"Forgot PIN" selectot:sel];