我对uibutton有一些问题。我想要一个按钮突出显示按下但是当按下其他按钮时不亮,但我无法让前一个按钮不亮。任何人都可以建议吗?
@interface ViewController : UIViewController
{
UIButton *button1;
UIButton *button2;
}
@property (nonatomic, retain) IBOutlet UIButton *button1;
@property (nonatomic, retain) IBOutlet UIButton *button2;
-(IBAction)button1:(id)sender;
-(IBAction)button2:(id)sender;
-(void) highlightButton: (UIButton *) button;
-(void) unhighlightButton: (UIButton *) button;
@end
@interface ViewController ()
@end
@implementation ViewController
@synthesize button1, button2;
-(IBAction)button1:(id)sender
{
[self performSelector:@selector(highlightButton:) withObject:sender afterDelay:0.0];
[button2 performSelector:@selector(unhighlightButton:) withObject:button2 afterDelay:0.0];
}
-(IBAction)button2:(id)sender
{
[self performSelector:@selector(highlightButton:) withObject:sender afterDelay:0.0];
[button1 performSelector:@selector(unhighlightButton:) withObject:button1 afterDelay:0.0];
}
-(void) highlightButton:(UIButton *)button
{
[button setHighlighted:YES];
}
-(void) unhighlightButton:(UIButton *)button
{
[button setHighlighted:NO];
}
@end
答案 0 :(得分:1)
由于您正在使用属性,因此请以两种方式更改这两行:
[self performSelector:@selector(unhighlightButton:) withObject:self.button2 afterDelay:0.0];
和
[self performSelector:@selector(unhighlightButton:) withObject:self.button1 afterDelay:0.0];
1)属性应以“self.
”
2)您正在调用视图控制器中的方法“unhighlightButton:
”,因此您需要在“self
”上调用它而不是“button
”。 “button
”通过“withObject:
”参数传递。
为什么使用“performSelector
”方法呢?
您可以重写其中一个操作方法:
-(IBAction)buttonTouched:(id)sender
{
[sender setHighlighted: YES];
if(sender == self.button1)
{
[self.button2 setHighlighted: NO];
} else {
[self.button1 setHighlighted: NO];
}
}
并将两个按钮指向一个IBAction。
答案 1 :(得分:1)
首先检查IBOutlet
和IBAction
连接是否正确连接。
-(IBAction)button1:(id)sender
{
[self performSelector:@selector(highlightButton:) withObject:sender afterDelay:0.0];
[self performSelector:@selector(unhighlightButton:) withObject:button2 afterDelay:0.0];
}
-(IBAction)button2:(id)sender
{
[self performSelector:@selector(highlightButton:) withObject:sender afterDelay:0.0];
[self performSelector:@selector(unhighlightButton:) withObject:button1 afterDelay:0.0];
}
-(void) highlightButton:(UIButton *)button
{
[button setHighlighted:YES];
}
-(void) unhighlightButton:(UIButton *)button
{
[button setHighlighted:NO];
}
答案 2 :(得分:0)
您还可以使用UIButton的selected属性: 对于两个按钮选择器将是相同的“buttonTouched”
-(IBAction)buttonTouched:(id)sender {
button1.selected = NO;
button2.selected = NO;
if (sender == button1) {
button1.selected = YES;
} else if (sender == button2) {
button2.selected = YES;
}
}
试试这个。
答案 3 :(得分:0)
-(IBAction)button1:(id)sender
{
button1.highlighted = YES;
button2.highlighted = NO;
}
-(IBAction)button2:(id)sender
{
button2.highlighted = YES;
button1.highlighted = NO;
}
让我知道它的工作与否!!!!!
快乐编码!!!!