How to make toggle image button instead of UIBarButtonItem in iphone programming?
I have to make a button in UINavigationBar, the button should toggle between restart state and cancel state, and it should call
-(void)RestartMethod {}
at restart state and should call method
-(void) cancelMethod {}
at cancel state of UIBarButtonItem,both states are using images like start.png and calcel.png
I tried by making two images and add and remove targets开发者_开发技巧,b but facing some bad-exec issues, how can I do it? Help!
item1=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"DoneUp3.png"] style:UIBarButtonItemStylePlain target:self action:@selector(action1)];
item2=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"Pin.png"] style:UIBarButtonItemStylePlain target:self action:@selector(action2)];
-(void)action1{self.navigationItem.rightBarButtonItem = item2;}
-(void)action2{self.navigationItem.rightBarButtonItem = item1;}
Create two buttons with two different targets. When one button is clicked do whatever you want the action to be and replace the button with button number two. If button number two is clicked, replace that with button number 1.
Why not use a segment control instead of toggle button? Even if you insist on using a single button to toggle, this is how I would achieve it.
Have a bool declare the initial state
BOOL buttonOn = NO;
Embed the first button with initial image pointing to one selector
- Inside selector take action based on this boolean. Change state and change this boolean's value too. No need to have two different selectors. Call appropriate functions to do stuff inside this selector.
i think this can help you:
CGRect frameimg = CGRectMake(0, 0, image3.size.width, image3.size.height);
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:[UIImage imageName:@"start.png"] forState:UIControlStateNormal];
[someButton setBackgroundImage:[UIImage imageName:@"calcel.png"] forState:UIControlStateSelected];
[someButton addTarget:self action:@selector(backButtonPress:)forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem=mailbutton;
[mailbutton release];
New write backButtonPress: method:
-(void)backButtonPress:(id)sender{
UIButton *tmpButton = (UIButton *)sender;
tmpButton.selected = [tmpButton isSelected]?NO:YES;
if (tmpButton.selected) {
// call cancelMethod or write RestartMethod code here
}
else{
// call RestartMethod or write RestartMethod code here
}
}
精彩评论