我有一个视图,我以编程方式创建了8个按钮。按钮的标题颜色为白色。我想在点击时将按钮标题的颜色更改为绿色。如果我点击任何其他按钮,之前点击的按钮标题颜色应该变为白色,当前按钮标题颜色应该变为绿色。
怎么做?
答案 0 :(得分:11)
像这样初始化所有按钮
[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;
}
答案 1 :(得分:0)
为所有按钮创建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];
}
答案 2 :(得分:0)
设置按钮的控制状态:
[btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected];
[btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
[btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];