我有一个视图,并在其中以编程方式创建了一些 8 个按钮。按钮的标题颜色为白色。我想在单击时将按钮标题的颜色更改为绿色。如果我单击任何其他按钮,先前单击的按钮标题颜色应变为白色,当前按钮标题颜色应变为绿色。
怎么做?
我有一个视图,并在其中以编程方式创建了一些 8 个按钮。按钮的标题颜色为白色。我想在单击时将按钮标题的颜色更改为绿色。如果我单击任何其他按钮,先前单击的按钮标题颜色应变为白色,当前按钮标题颜色应变为绿色。
怎么做?
像这样初始化所有按钮
[mybutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[mybutton setTitleColor:[UIColor greenColor] forState:UIControlStateSelected];
[mybutton addTarget:self action:@selector(onclick:) forControlEvents:UIControlEventTouchUpInside];
然后在单击时更改按钮的选定状态
-(void)onclick:(id)sender{
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
}
IBAction
为所有按钮创建,创建一个属性@property (strong, nonatomic) UIButton *currentButton
。在操作中执行以下操作:
-(IBAction)buttonClicked:(id)sender
{
UIButton *buttonSender = (UIButton *)sender;
[self.currentButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
self.currentButton = buttonSender;
[self.currentButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
设置按钮的控制状态:
[btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected];
[btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
[btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];