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];
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
I want to set custom back bar button for all controllers in the app. I tried using this:
[[UIBarButtonItem appearance]
setBackButtonBackgroundImage:backButtonImage
forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
It sets the image. That's OK. But, what i really want to do is that, i just want a custom button for back bar button which does not contain any title etc. The code above works, but it adds automated titles and resizes the back bar button item. My need is to have a fixed frame, no-title back bar button item for all controllers in the app.
I've resolved it. Just make a category over UIViewController and import it in prefix.pch file. Then write a method: customViewWillAppear: and swizzle it with viewWillAppear method:
+(void)load{
Method viewWillAppear = class_getInstanceMethod(self, #selector(customViewWillAppear:));
Method customViewWillAppear = class_getInstanceMethod(self, #selector(viewWillAppear:));
method_exchangeImplementations(viewWillAppear, customViewWillAppear);
}
Add the above method to that category class. Then implement your customViewWillAppear method like this:
-(void)customViewWillAppear:(BOOL)animated{
[self customViewWillAppear:animated];
if([self.navigationController.viewControllers indexOfObject:self] != 0 && !self.navigationItem.hidesBackButton){
UIBarButtonItem *cancelBarButton = nil;
UIButton* cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[cancelButton addTarget:self action:#selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
[cancelButton setBackgroundImage:[UIImage imageNamed:#"yourImage.png"] forState:UIControlStateNormal];
[cancelButton sizeButtonToFit];
cancelBarButton = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
NSMutableArray * leftButtons = [NSMutableArray arrayWithObject:cancelBarButton];
[leftButtons addObjectsFromArray:self.navigationItem.leftBarButtonItems];
[self.navigationItem setLeftBarButtonItem:nil];
[self.navigationItem setLeftBarButtonItems:leftButtons];
}
[self.navigationItem setHidesBackButton:YES];
}
-(void)popViewControllerWithAnimation{
[self.navigationController popViewControllerAnimated:YES];
}
Now, for every controller in your code, you have a custom back button. This took me a lot of time to implement and figure out. Hope it'll help you guys all too.
EDIT:
Please use the following code to support iOS7> back swipe feature;
UIImage *image = [UIImage imageForName:#"some_image"];
navBar.backIndicatorImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
navBar.backIndicatorTransitionMaskImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
Create a base view controller and add the following code;
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:nil action:nil];
}
I've had a similar problem before and I've searched everywhere for a solution.
The only one I've found, which works for your problem was to implement in EVERY view controller a UILeftBarButton which does the popping.
You can change the background image the way you're doing, but if you set the text to nil or empty text (""), you're button just won't show up.
You also can't change the View of the UIBackBarButton, only it's text (so no custom button).
What i did, was set the backbutton title label alpha to zero, using appearance proxy.
My code in ViewDidLoad:
// Set back button image
if ([[self.navigationController viewControllers] objectAtIndex:0] != self) {
UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
btnBack.frame = CGRectMake(0,0,38,30);
[btnBack setBackgroundImage:[UIImage imageNamed:#"NavigationBarBackButton"] forState:UIControlStateNormal];
[btnBack addTarget:self.navigationController action:#selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
[self.navigationItem setLeftBarButtonItem:leftBtn];
}
You could write a category like this,
//
// UINavigationItem+BarAditions.h
//
// Created by Satheeshwaran on on 7/5/13.
//
#import <Foundation/Foundation.h>
#interface UINavigationItem (PersonaAddition)
- (void)setCustomBackButton;
#end
//
// UINavigationItem+BarAditions.m
//
// Created by Satheeshwaran on on 7/5/13.
//
#import "UINavigationItem+PersonaAddition.h"
#implementation UINavigationItem (PersonaAddition)
- (void)setCustomBackButton
{
//customize ur back button here.
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame=CGRectMake(0, 0, 60, 30);
[backButton addTarget:target action:#selector(didPressLeftItem:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
self.leftBarButtonItem = barItem;
}
and import this category in all ur files and call the setCustomBackButton in all ur classes. This works fine for me, even in iOS 7.
In ViewDidLoad of all ur classes.
- (void)viewDidLoad
{
[super viewDidLoad];
[self.navigationItem setCustomBackButton];
}
try this code:
UIButton *tempbtn = [[UIButton alloc] init];
[tempbtn setImage:[UIImage imageNamed:#"testbtn.png"] forState:UIControlStateNormal];
UIBarButtonItem *temp = [[UIBarButtonItem alloc] initWithCustomView:tempbtn];
self.navigationItem.rightBarButtonItem = temp;
In my application there are many UIViewControllers with UINavigationControllers. There must be a "back" button and a "home" UIButton on the UINavigationBar. All of this works fine.
But some of my UIViewControllers have long names, and sometimes there is too small place left for it. I'm trying to replace the original label of the "back" button (it shows the title of the previous view) with a custom "Back", but whatever I tried it didn't work:
// Title didn't change
[self.navigationItem.backBarButtonItem setTitle:#"Back"];
// Action didn't set, no response from button ( button didn't do anything )
[self.navigationItem.leftBarButtonItem
setAction:self.navigationItem.backBarButtonItem.action];
And I need the "back" button to have a style like in this question: Draw custom Back button on iPhone Navigation Bar
Try the following. It will definitely work:
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *buttonImage = [UIImage imageNamed:#"back.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
[button addTarget:self action:#selector(back) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = customBarItem;
[customBarItem release];
}
- (void)back {
[self.navigationController popViewControllerAnimated:YES];
}
Make sure you have an button image with the size of a navigation bar back button in your resource folder with name back.png.
Feel free if any other assistance is required.
Target:
customizing all back button on UINavigationBar to an white icon
Steps:
1. in "didFinishLaunchingWithOptions" method of AppDelete:
UIImage *backBtnIcon = [UIImage imageNamed:#"navBackBtn"];
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"7.0")) {
[UINavigationBar appearance].tintColor = [UIColor whiteColor];
[UINavigationBar appearance].backIndicatorImage = backBtnIcon;
[UINavigationBar appearance].backIndicatorTransitionMaskImage = backBtnIcon;
}else{
UIImage *backButtonImage = [backBtnIcon resizableImageWithCapInsets:UIEdgeInsetsMake(0, backBtnIcon.size.width - 1, 0, 0)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -backButtonImage.size.height*2) forBarMetrics:UIBarMetricsDefault];
}
2.in the "viewDidLoad" method of the common super ViewController class:
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"7.0")) {
UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:#""
style:UIBarButtonItemStylePlain
target:nil
action:nil];
[self.navigationItem setBackBarButtonItem:backItem];
}else{
//do nothing
}
Try this
UIBarButtonItem *backBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStylePlain target:self action:#selector(popViewController)];
[self.navigationItem setBackBarButtonItem:backBarBtnItem];
- (void)popViewController
{
[self.navigationController popViewControllerAnimated:YES];
}
If you're doing this all over the place like I am, you're better off implementing Anil's solution as a category:
#interface UIViewController (CustomBackButton)
- (void) setCustomBackButton;
- (void) back;
#end
#implementation UIViewController (CustomBackButton)
- (void) setCustomBackButton
{
UIImage *buttonImage = [UIImage imageNamed:#"back.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
[button addTarget:self action:#selector(back) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = customBarItem;
}
- (void) back
{
[self.navigationController popViewControllerAnimated:YES];
}
#end
More simply:
UIBarButtonItem *barBtnItem =
[[UIBarButtonItem alloc]initWithTitle:#"Indietro"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(pop)];
[barBtnItem setTintColor:[UIColor whiteColor]];
self.navigationItem.leftBarButtonItem = barBtnItem;
Suppose you have two controllers - Controller1 and Controller2. Controller2 is pushed from Controller1. So before pushing the Controller2 on the navigationController from Controller1
Controller2 *controller2 = [[[Controller2 alloc] init]autorelease];
self.navigationItem.hidesBackButton = YES;
Now, in the viewDidLoad: method of Controller2, add the following snippet
UIBarButtonItem *backBarButtonItem =[[[UIBarButtonItem alloc]initWithTitle:#"Back" style:UIBarButtonItemStyleBordered target:self action:#selector(goBackToAllPets:)]autorelease];
self.navigationItem.leftBarButtonItem = backBarButtonItem;
and in the backButtonClicked method, you can perform the checks you want to.
I need to change the default title value of the back button in a navigationcontroller to something else.
I am trying this with the following code:
UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle: #"Terug" style: UIBarButtonItemStyleBordered target:nil action:nil];
self.navigationItem.backBarButtonItem = newBackButton;
[newBackButton release];
i also tried:
UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle: #"Terug" style: UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = newBackButton;
[newBackButton release];
I am using this code at the end of the viewDidLoad.
I am able to create a normal button (square) with the following code:
UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle: #"Terug" style: UIBarButtonItemStyleBordered target:nil action:nil];
self.navigationItem.leftBarButtonItem = newBackButton;
[newBackButton release];
The problem with this solution is that I need to create a seperate method that pop's the view controller. Another issue would be the shape of the button, I need an arrow shaped button.
do you have any idea?
If you want to have a custom back button you need to create new one and assign a new selector to it.
The backBarButtonItem is not editable, so you need to set the leftBarButtonItem.
This is how you can create a custom back button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:NSLocalizedString(#"Back", nil) forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:#"back.png"] forState:UIControlStateNormal];
[button addTarget:navigationController action:#selector(backAction:)forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:button];
navigationController.navigationItem.leftBarButtonItem = backButton;
[backButton release];
And this is the selector to simulate the back button
- (IBAction)backAction:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
}
There is a simple solution
lets say you are moving from viewA to viewB
just before moving from viewA to viewB change the title of viewA
for example:
-(void)moveToViewB
{
// Add this line
self.title = #"Terug";
// and push the new view as normal
[self.navigationController pushViewController:viewB animated:NO];
}
Call this button from your 'viewDidLoad' method.
- (void)addCustomBackButton {
/* enter your image name and size here */
UIImage *backImage = [UIImage imageNamed:#"back_btn.png"];
CGRect buttonRect = CGRectMake(5.0f, 0.0f, 12.0f, 20.0f);
/* enter your image name and size here */
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton addTarget:self action:#selector(backAction) forControlEvents:UIControlEventTouchUpInside]; // implemeent 'backAction' method in each VC
[backButton setFrame:buttonRect];
UIImageView *imageView = [[UIImageView alloc] initWithImage:backImage];
[imageView setFrame:buttonRect];
[backButton addSubview:imageView];
UIBarButtonItem *homeButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
self.navigationItem.leftBarButtonItem = homeButtonItem;
}
[Or, make it a class method of a 'Utitlity' class and call it as a class method in each viewContorller it is required.]
Also, don't forget to implement the 'backAction', something like this:
- (void)backAction
{
[self.navigationController popViewControllerAnimated:YES];
}
Happy coding!
I have the following code inside my #interface FriendsNavController : UINavigationController class implementation. The code is executed. I just don't know why it's not showing the button...
- (void)viewDidLoad {
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:#"Add Event" style:UIBarButtonItemStylePlain target:self action:#selector(refreshPropertyList)];
self.navigationItem.rightBarButtonItem = button;
[button release];
[super viewDidLoad];
}
EDIT: I think I misread your question. I set the navigationItem.rightBarButtonItem in the viewDidLoad of the controller that I push onto the navigation controller's stack, not in the viewDidLoad of the navigation controller. I think this is what you'll need to do as well.
Perhaps the call to [super viewDidLoad] is setting the navigation item's buttons back to the default (i.e., none). In my navigation-based app, I make the [super viewDidLoad] call before my code, like this:
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:#"Add Event" style:UIBarButtonItemStylePlain target:self action:#selector(refreshPropertyList)];
self.navigationItem.rightBarButtonItem = button;
[button release];
}
and the right button is appearing correctly.