I'm trying to create a toggle button in a navigation bar in iOS5 with UISegmentControl. The problem I'm having is that setSelectedSegmentIndex isn't persistent, i.e. when the users clicks one of the segments, it's action gets called but it isn't set as selected. My current code looks like this:
// In viewDidLoad
toolSegment = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:
[UIImage imageNamed:#"ToolPenIcon.png"],
[UIImage imageNamed:#"TextIcon.png"],
nil]];
[toolSegment addTarget:self action:#selector(changeMode:) forControlEvents:UIControlEventValueChanged];
toolSegment.frame = CGRectMake(0, 0, 85, 30);
toolSegment.segmentedControlStyle = UISegmentedControlStyleBezeled;
toolSegment.momentary = YES;
[toolSegment setSelectedSegmentIndex:1];
UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:toolSegment];
self.navigationItem.rightBarButtonItem = segmentBarItem;
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
- (void)changeMode:(id)sender
{
UISegmentedControl * control = (UISegmentedControl*)sender;
if (control.selectedSegmentIndex == 0) {
NSLog(#"Print");
[toolSegment setSelectedSegmentIndex:0];
} else {
// Should change the selected index.
[toolSegment setSelectedSegmentIndex:1];
[pageView changeToText];
if (pageView.canvas.image != nil) {
[self createNewPage];
}
writing = YES;
}
}
Any tips on what I might be doing wrong would be appreciated.
You probably don't want the control to be in momentary mode as this would allow multi selection. Set momentary to NO.
Related
I'm trying to figure out how can I achieve something like this:
This is a toolbar and I'd like to keep the button title text without having to create the whole image with icon AND text. How can I add the icon to the left of the UIBarButtonItem while keeping the text set with:
UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Button" style:UIBarButtonItemStyleBordered target:nil action:nil];
EDIT
This is what I achieved with the following code:
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:#"Test"] forState:UIControlStateNormal];
[customButton setTitle:#"Button" forState:UIControlStateNormal];
customButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
[customButton sizeToFit];
UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
Two issues here: the first is the size of the UIButton and the second is that, as you can see from the gif, the button doesn't animate properly when I tap inside the button and when I release the tap. Any ideas?
You can embed a UIButton as a custom view inside your UIBarButtonItem. You can create your UIButton however you want, including with an image and text, using -setImage:forState: and -setTitle:forState:.
UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:#"image"] forState:UIControlStateNormal];
[customButton setTitle:#"Button" forState:UIControlStateNormal];
[customButton sizeToFit];
UIBarButtonItem* customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
self.navigationItem.leftBarButtonItem = customBarButtonItem; // or self.navigationItem.rightBarButtonItem
Note that when doing this, you'll need to attach your IBAction methods to customButton, not to customBarButtonItem.
For more info, see the documentation for initWithCustomView:.
You can also do all of this in interface builder just by dragging a UIButton to the left bar button/right bar button slot on a navigation bar.
I was not satisfied with all solutions found on stack overflow becauseI like how UIBarButtonItenm convert images so they are displayed correctly and they can be changed with tint colour. So i discovered this solution that I can use nicely with not much code... End effect is similar to toolbar in facebook and other current apps...
When you change tint colour of view contained in UIBArButtonItem colours of image and title change accordingly, really cool , I do not have to create special images at all.
This code is called from each button like that Competition Button, and also Button is set as referencing outlet...
- (void)selectButton:(UIButton *)sender {
_competitionButton.superview.tintColor = [UIColor lightGrayColor];
_usersButton.superview.tintColor = [UIColor lightGrayColor];
_managementButton.superview.tintColor = [UIColor lightGrayColor];
sender.superview.tintColor = [UIColor whiteColor];
}
- (IBAction)onCompetitionButtonClick:(UIButton *)sender {
[self selectButton:sender];
[_scrollView scrollToPage:0 of:3];
}
In Button like that titled Competition there is only title and in bar button item there is image... This is how I have setup it and it works , maybe there are also other possibilities..
So I managed to do my solution programatically... Some users where complaining it does not work ... So how to create UTToolbar with image and item so that you can change color of button by tint and it magically alters image as well as title label ? My UI editor solution works for sure...
In this code can clarify things more and you can do it programatically either...
- (void)loadToolbar {
NSMutableArray *items = NSMutableArray.new;
[items add:[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]];
for (uint pageIndex = 0; pageIndex < _controllers.count; ++pageIndex) {
UIView *itemView = [UIView.alloc initWithFrame:CGRectMake(0, 0, 100, 44)];
itemView.backgroundColor = [UIColor clearColor];
itemView.tintColor = [UIColor orangeColor];
[itemView addSubview:[self createToolbarForItemView:pageIndex]];
[itemView addSubview:[self createButtonForItemView:pageIndex]];
UIBarButtonItem *item = [UIBarButtonItem.alloc initWithCustomView:itemView];
item.style = UIBarButtonItemStylePlain;
[items add:item];
[items add:[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]];
}
[_toolbar setItems:items];
}
- (UIButton *)createButtonForItemView:(uint)pageIndex {
UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeSystem];
itemButton.frame = CGRectMake(0, 0, 100, 44);
itemButton.titleLabel.font = [UIFont systemFontOfSize:11];
itemButton.contentEdgeInsets = UIEdgeInsetsMake(30, 0, 0, 0);
itemButton.text = [_controllers[pageIndex] tabTitle];
itemButton.touchUp = ^(UIButton *sender) {
for (UIButton *button in _buttons) button.superview.tintColor = UI.toolBarInactiveButtonTextColor;
sender.superview.tintColor = UI.toolBarActiveButtonTextColor;
[self showPage:pageIndex];
};
[_buttons add:itemButton];
return itemButton;
}
- (UIToolbar *)createToolbarForItemView:(uint)pageIndex {
UIToolbar *itemToolbar = [UIToolbar.alloc initWithFrame:CGRectMake(0, 0, 100, 44)];
itemToolbar.tintColor = nil;
itemToolbar.barStyle = _toolbar.barStyle;
itemToolbar.translucent = _toolbar.translucent;
UIBarButtonItem *imageItem = [_controllers[pageIndex] tabImageItem];
imageItem.style = UIBarButtonItemStylePlain;
imageItem.tintColor = nil;
imageItem.imageInsets = UIEdgeInsetsMake(-10, 0, 0, 0);
itemToolbar.items = #[
[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil],
imageItem,
[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]
];
return itemToolbar;
}
I solved this problem as follows:
[Button **setTitleColor**:[UIColor colorWithRed:129/255.0f green:124/255.0f blue:110/255.0f alpha:1.0f] forState:**UIControlStateHighlighted**];
I have a view that has labels being dynamically added by the user. If the use would like to edit any of the labels, they press a button and all the labels get highlighted with a delete button and move button. (Editing is another bridge I’ll cross later).
My issue is: What is the best way to turn the buttons on and off? I have a method that turns the buttons on… but I am at a loss as to how I turn them off when done editing. Do I need to tag my buttons and then just ‘hide them’? Or do I just remove them all totally? How do I parse all the buttons that are turned on then, turn them off. Do I need to put them in an array as well? The labels are tagged with unique numbers so I know which label is which.
Any thoughts? Guidance? If I am doing it all wrong please tell me.
Here is a couple methods I have:
- (void) showEditableText {
// Parse the array of labels
if(textArray.count > 0){
for(UILabel *label in textArray){
//Add Delete Button
UIImage * delButtonImage = [UIImage imageNamed:#"GUI_Delete.png"];
UIButton * delThisButton = [[UIButton alloc] initWithFrame:CGRectMake(label.frame.origin.x - delButtonImage.size.width, label.frame.origin.y - delButtonImage.size.height, delButtonImage.size.width, delButtonImage.size.height)];
[delThisButton setBackgroundImage:delButtonImage forState:UIControlStateNormal];
[delThisButton addTarget:self action:#selector(deleteThisLabel:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:delThisButton];
//Add a move button
UIImage * moveButtonImage = [UIImage imageNamed:#"GUI_Move.png"];
UIButton * moveThisButton = [[UIButton alloc] initWithFrame:CGRectMake((label.frame.origin.x + label.frame.size.width + moveButtonImage.size.width), label.frame.origin.y - moveButtonImage.size.height, moveButtonImage.size.width, moveButtonImage.size.height)];
[moveThisButton setBackgroundImage:moveButtonImage forState:UIControlStateNormal];
[moveThisButton addTarget:self action:#selector(moveThisLabel:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:moveThisButton];
//Make the text highlighed
label.highlighted = YES;
label.backgroundColor = [UIColor colorWithRed:203/255.0f green:230/255.0f blue:239/255.0f alpha:1];
label.highlightedTextColor = [UIColor redColor];
}
}
}
- (void) doneEditingText {
if(textArray.count > 0){
for(UILabel *label in textArray){
//THIS IS WHERE I AM STUCK? WHAT DO I DO?
label.highlighted = NO;
label.backgroundColor = [UIColor clearColor];
}
}
}
//inside your first method set the same tag to your all buttons
-(void) showEditableText {
........
.......
.......
delThisButton.tag = 10;
moveThisButton.tag = 10;
}
//inside your second method delete all the subviews using this tag as shown below..
-(void) doneEditingText {
if(textArray.count > 0){
for(UILabel *label in textArray){
..............................
//THIS IS WHERE I AM STUCK? WHAT DO I DO?
for (UIView *subview in [self.view subviews]) {
if (subview.tag == 10) {
[subview removeFromSuperview];
}
}
...............................
label.highlighted = NO;
label.backgroundColor = [UIColor clearColor];
}
}
}
Move all your buttons code to viewDidLoad, hide them (button.hidden = YES). When you start/finish editing your text, unhide and hide your buttons. You need to have an ivar to contain the buttons too. So add them in your .h file.
Try This
UIView * seletetButton = nil;
for (UIView * btn in self.view.subviews){
if ([btn isKindOfClass:[UIButton class]])
{
if (seletetButton.tag != btn.tag)
{
[btn removeFromSuperview];
}
}
}
after going through the questions related to UINavigationController item i came to post my exact problem ..
firstly i am not add a UINavigationController in MainWindow.xib i created and adding UINavigationController in AppDelegate file
after that in a UIViewController (not in rootViewController) class I have to add a rightbarbutton of Done type I am
adding it in a searchbarDelegate Method showing as bold:-
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
//This method is called again when the user clicks back from teh detail view.
//So the overlay is displayed on the results, which is something we do not want to happen.
if(exhibDataObj.searching)
return;
//Add the overlay view.
if(ovController == nil)
ovController = [[OverlayViewController alloc] initWithNibName:#"OverlayView" bundle:[NSBundle mainBundle]];
CGFloat yaxis = self.navigationController.navigationBar.frame.size.height;
CGFloat width = self.view.frame.size.width;
CGFloat height = self.view.frame.size.height;
//Parameters x = origion on x-axis, y = origon on y-axis.
CGRect frame = CGRectMake(0, yaxis, width, height);
ovController.view.frame = frame;
ovController.view.backgroundColor = [UIColor grayColor];
ovController.view.alpha = 0.5;
ovController.rvController = self;
[self.theTableView insertSubview:ovController.view aboveSubview:self.parentViewController.view];
exhibDataObj.searching = true;
letUserSelectRow = NO;
self.theTableView.scrollEnabled = NO;
//Add the done button.
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:#selector(doneSearching_Clicked:)];
}
but this never works .
Any help will be more appreciable.
I've tested your code real quick and it seems to be working fine for me, however, I've had the same problem once back then it turned out I was setting the rightBarButtonItem to nil in my viewDidLoad method after setting it to a button. you should make sure your not making the same mistake somehow.
However if that does not work for you you can always try setting a custom button to it:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 30, 30)];
button.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"done.png"]];
[button addTarget:self action:#selector(doneButtonClicked) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationController.visibleViewController.navigationItem.rightBarButtonItem = customItem;
I've got a UITableViewController subclass that is subclassed by two other classes. In some of the cells of both tables I have an image that the user can click on to perform an action. It all works and I'm happy except that in one of the 2 subclasses the first row of that table has an issue. You can only click the image by clicking to the rightmost edge of the image. If you click in the body of the image it calls the table's didSelectRowAtIndexPath instead.
What boggles me is that it works in the other class for all rows and even in the one it doesn't work for it works in all the other rows where that image shows up. Here's the code I'm using to add the image and gesture recognizer into my cell:
UIImageView *imgparent = [[UIImageView alloc] initWithFrame:CGRectMake(offsetleftmain, 24.0, 14.0, 16.0)];
imgparent.image = [UIImage imageNamed:#"item_open.png"];
imgparent.tag = ITEMOPENTAG;
// add listener
imgparent.userInteractionEnabled = YES;
UITapGestureRecognizer *singleFingerDTapParent = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(loadChildren:)];
[imgparent addGestureRecognizer:singleFingerDTapParent];
[singleFingerDTapParent release];
[cell.contentView addSubview:imgparent];
[imgparent release];
I'm testing in the simulator by the way. I've tried replacing the image with a button but still the problem persists. Any ideas?
EDIT: Here's the beginnings of the code that is called when the image is clicked. Again, this works but in the case of that one row it only works if you click on the right edge of the image. I've attached a screenshot to illustrate. The first circle indicates where I have to tap in order to get my gesture to be called. The second shows an example in the very same table that allows you to click the entire image. I'm confounded.
- (void)loadChildren:(UIGestureRecognizer *)gestureRecognizer {
NSLog(#"loadChildren");
// get the cell
UITableViewCell *cell = (UITableViewCell *)gestureRecognizer.view.superview.superview;
UIImageView *imgvw = (UIImageView *)[cell viewWithTag:ITEMOPENTAG]; // open arrow
[imgvw setHidden:YES]; // hide open arrow
imgvw = (UIImageView *)[cell viewWithTag:ITEMCLOSETAG]; // close arrow
[imgvw setHidden:NO]; // show close arrow
// get the record for the cell
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
}
EDIT: Here's the complete tableView:cellForRowAtIndexPath:indexPath. Keep in mind that it's being called from the cellForRowAtIndexPath of 2 other subclasses of this class, each simply passing in an identifier withType:
- (UITableViewCell *)tableView:(UITableView *)tv
cellForRowAtIndexPath:(NSIndexPath *)indexPath
withType:(NSString *)s_type
{
UITableViewCell *cell = nil;
// if dealing with empty region then show no tasks cell
if(s_type == #"noTasksCell"){
cell = [tv dequeueReusableCellWithIdentifier:#"noTasksCell"];
if( cell == nil ) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"noTasksCell"] autorelease];
}
cell.textLabel.text = #"No tasks";
cell.textLabel.textColor = [UIColor lightGrayColor];
cell.textLabel.font = [UIFont systemFontOfSize:14];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
UILabel *lblMain;
NSDictionary *o_rec = [self getRecForPath:indexPath];
NSString *s_cell = #"rowCell";
BOOL b_parent = NO;
BOOL b_parentOpen = NO;
BOOL b_child = NO;
BOOL b_checked = NO;
if([self isParent:indexPath]){
b_parent = YES;
b_parentOpen = !([o_rec objectForKey:#"b_open"] == nil || [[o_rec objectForKey:#"b_open"] isEqualToNumber:[NSNumber numberWithInt:0]]);
s_cell = [s_cell stringByAppendingString:#"Parent"];
}
if([o_rec objectForKey:#"b_child"] != nil){
b_child = YES;
s_cell = [s_cell stringByAppendingString:[NSString stringWithFormat:#"Child%#",[o_rec objectForKey:#"indent"]]];
}
if([[o_rec objectForKey:#"checked"] isEqualToNumber:[NSNumber numberWithInt:1]]){
b_checked = YES;
s_cell = [s_cell stringByAppendingString:#"isComplete"];
}
// add the following to the name:
// - project id
// - width of table to the name so that rotations will change the cell dequeue names
// - priority
s_cell = [s_cell stringByAppendingFormat:
#"Proj%#Width%dP%#"
,[o_rec objectForKey:#"project_id"]
,(int)tv.bounds.size.width
,[[o_rec objectForKey:#"priority"] stringValue]
];
cell = [tv dequeueReusableCellWithIdentifier:s_cell];
if( cell == nil ) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:s_cell] autorelease];
cell.textLabel.hidden = YES; // hide the regular text label
cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
cell.selectedBackgroundView.backgroundColor = [delegate colorForHexWithAlpha:0xffcc66ff];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
int offsetleftmain = 10;
if(b_child){
offsetleftmain += ([[o_rec objectForKey:#"indent"] intValue]-1) * 18;
}
if(b_parent){
// parent arrow
UIImageView *imgparent = [[UIImageView alloc] initWithFrame:CGRectMake(offsetleftmain, 24.0, 14.0, 16.0)];
imgparent.image = [UIImage imageNamed:#"item_open.png"];
imgparent.tag = ITEMOPENTAG;
// add listener
imgparent.userInteractionEnabled = YES;
UITapGestureRecognizer *singleFingerDTapParent = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(loadChildren:)];
singleFingerDTapParent.numberOfTapsRequired = 1;
singleFingerDTapParent.numberOfTouchesRequired = 1;
[imgparent addGestureRecognizer:singleFingerDTapParent];
[singleFingerDTapParent release];
[cell.contentView addSubview:imgparent];
[imgparent release];
// close arrow
UIImageView *imgparent2 = [[UIImageView alloc] initWithFrame:CGRectMake(offsetleftmain-2, 24.0, 16.0, 14.0)];
imgparent2.image = [UIImage imageNamed:#"item_close.png"];
imgparent2.tag = ITEMCLOSETAG;
imgparent2.userInteractionEnabled = YES;
UITapGestureRecognizer *singleFingerDTapParent2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(hideChildren:)];
[imgparent2 addGestureRecognizer:singleFingerDTapParent2];
[singleFingerDTapParent2 release];
[cell.contentView addSubview:imgparent2];
[imgparent2 release];
}
offsetleftmain += 18;
// checkbox
UIImageView *imgchk = [[UIImageView alloc] initWithFrame:CGRectMake(offsetleftmain, 20.0, 24.0, 24.0)];
imgchk.image = [UIImage imageNamed:#"check_empty.png"];
imgchk.tag = EMPTYCHECKTAG;
// add listener
imgchk.userInteractionEnabled = YES;
UITapGestureRecognizer *singleFingerDTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(checkOnItem:)];
[imgchk addGestureRecognizer:singleFingerDTap];
[singleFingerDTap release];
[cell.contentView addSubview:imgchk];
[imgchk release];
// checked checkbox
UIImageView *imgchk2 = [[UIImageView alloc] initWithFrame:CGRectMake(offsetleftmain, 20.0, 24.0, 24.0)];
imgchk2.image = [UIImage imageNamed:#"check_checked.png"];
imgchk2.tag = CHECKTAG;
// add listener
imgchk2.userInteractionEnabled = YES;
UITapGestureRecognizer *singleFingerDTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(checkOffItem:)];
[imgchk2 addGestureRecognizer:singleFingerDTap2];
[singleFingerDTap2 release];
[cell.contentView addSubview:imgchk2];
[imgchk2 release];
offsetleftmain += 28;
// main label
lblMain = [[UILabel alloc] initWithFrame:CGRectMake(offsetleftmain, 22.0, tv.bounds.size.width-offsetleftmain-10, 30.0)];
lblMain.tag = MAINLABELTAG;
lblMain.numberOfLines = 4;
lblMain.font = delegate.font_dflt;
// change color based on priority
if (5-[[o_rec objectForKey:#"priority"] intValue] == 1)
lblMain.textColor = [UIColor redColor];
else if (5-[[o_rec objectForKey:#"priority"] intValue] == 2)
lblMain.textColor = [delegate colorForHexWithAlpha:H_P2COLOR];
else if (5-[[o_rec objectForKey:#"priority"] intValue] == 3)
lblMain.textColor = [delegate colorForHexWithAlpha:H_P3COLOR];
[cell.contentView addSubview:lblMain];
[lblMain release];
// show action sheet for long press and hold
UILongPressGestureRecognizer *clicknHold = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(cellClicknHold:)];
[cell addGestureRecognizer:clicknHold];
[clicknHold release];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// task text
lblMain = (UILabel *)[cell viewWithTag:MAINLABELTAG];
lblMain.text = [self formatContent:[o_rec objectForKey:#"content"]];
CGRect newFrame = lblMain.frame;
newFrame.size.height = [[o_rec objectForKey:#"height"] floatValue];
//newFrame.size.height = [[o_rec objectForKey:#"height"] floatValue]+12;
lblMain.frame = newFrame;
// set checked status
[(UIImageView *)[cell viewWithTag:EMPTYCHECKTAG]
setHidden:[[o_rec objectForKey:#"checked"] boolValue]];
[(UIImageView *)[cell viewWithTag:CHECKTAG]
setHidden:![[o_rec objectForKey:#"checked"] boolValue]];
// show open arrow if dealing with parent cell
if (b_parent) {
//NSLog(#"b_parentOpen:%d",b_parentOpen);
[(UIImageView *)[cell viewWithTag:ITEMOPENTAG] setHidden:b_parentOpen];
[(UIImageView *)[cell viewWithTag:ITEMCLOSETAG] setHidden:!b_parentOpen];
}
return cell;
}
Just in case someone runs into a similar issue as rare as that may be maybe this will help avoid someone going bald pulling their hair out. So my problem wasn't with the tableView itself but a sidebar I have that is similar to the facebook sidebar that slides in and out. My sidebar has a tableview in it and that table has a header on it that for some reason when it was right beside my other table was somehow preventing clicks to the image in that first row. My solution was simply to position that sidebar view a little bit further offscreen away from the view it was beside instead of being right next to it. Problem solved. Thanks to all who tried to help me out.
I want to disabled the default back button of navigation controller
self.navigationItem.rightBarButtonItem.enabled = NO;
// Below code does not work since leftBarButtonItem is always nil.
self.navigationItem.leftBarButtonItem.enabled = NO;
I have done it with manually shown below, But Is there any property to disabled the default back button with just single line?
backButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 100, 30)];
[backButton setBackgroundImage:[UIImage imageNamed:#"backbutton_100.png"] forState:UIControlStateNormal];
[backButton addTarget:self action:#selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
[backButton setTitle:#" All Customers" forState:UIControlStateNormal];
backButton.titleLabel.font = [UIFont boldSystemFontOfSize:12];
[buttonView addSubview:backButton];
UIBarButtonItem* leftButton = [[UIBarButtonItem alloc] initWithCustomView:buttonView];
self.navigationItem.leftBarButtonItem = leftButton;
[leftButton release];
// Now it is working.
self.navigationItem.leftBarButtonItem.enabled = NO;
Its very easy ..... just try this out
self.navigationController.navigationBar.userInteractionEnabled = NO; //for disabling
self.navigationController.navigationBar.userInteractionEnabled = YES; //for again enabling
Using "hidesBackButton=YES" is really not an elegant solution, cause it HIDES the button which is not what we want. An acceptable work-around would be adding a UILabel to the window just over the back button at least disabling the touches on the button.
Add this method to your AppDelegate class:
- (void) disableLeftBarButtonItemOnNavbar:(BOOL)disable
{
static UILabel *l = nil;
if (disable) {
if (l != nil)
return;
l = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 160, 44)];
l.backgroundColor = [UIColor clearColor];
l.userInteractionEnabled = YES;
[self.window addSubview:l];
}
else {
if (l == nil)
return;
[l removeFromSuperview];
[l release];
l = nil;
}
}
You can call it like this from any view controller to disable:
MyAppDelegate *appDeleg = (MyAppDelegate *) [[UIApplication sharedApplication] delegate];
[appDeleg disableLeftBarButtonItemOnNavbar:YES];
To enable:
MyAppDelegate *appDeleg = (MyAppDelegate *) [[UIApplication sharedApplication] delegate];
[appDeleg disableLeftBarButtonItemOnNavbar:NO];
Call [self.navigationItem setHidesBackButton:YES]; for the view controller you do not want to have the back button. Then set the leftBarButtonItem as normal.
You can also use
[[_navigationController.topViewController.navigationItem leftBarButtonItem] setEnabled:NO]; // The top view controller on the stack.
[[_navigationController.visibleViewController.navigationItem leftBarButtonItem] setEnabled:NO];// Return modal view controller if it exists. Otherwise the top view controller.
you can use this when you want to disable or enable UIViewControler from Appdelegate, or any other viewcontroler.