我有一个视图,我在那里编程创建了一些8个按钮。按钮的标题颜色是白色。点击时,我想将按钮标题的颜色更改为绿色。如果我点击任何其他按钮,以前点击的按钮标题颜色应该变成白色,并且当前按钮标题颜色应该变成绿色。如何在点击时更改UIButton的标题颜色?
如何做到这一点?
我有一个视图,我在那里编程创建了一些8个按钮。按钮的标题颜色是白色。点击时,我想将按钮标题的颜色更改为绿色。如果我点击任何其他按钮,以前点击的按钮标题颜色应该变成白色,并且当前按钮标题颜色应该变成绿色。如何在点击时更改UIButton的标题颜色?
如何做到这一点?
初始化所有的按钮,这样
[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];
这是实际不是重复的问题。感谢您的正确答案@Bordz –