【问题标题】:How to change title color of UIButton when clicked? [duplicate]点击时如何更改 UIButton 的标题颜色? [复制]
【发布时间】:2013-10-09 09:43:00
【问题描述】:

我有一个视图,并在其中以编程方式创建了一些 8 个按钮。按钮的标题颜色为白色。我想在单击时将按钮标题的颜色更改为绿色。如果我单击任何其他按钮,之前单击的按钮标题颜色应变为白色,当前按钮标题颜色应变为绿色。

怎么做?

【问题讨论】:

  • 这实际上不是一个重复的问题。感谢您的正确答案@Bordz

标签: ios


【解决方案1】:

像这样初始化所有按钮

[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;
}

【讨论】:

    【解决方案2】:

    为所有按钮创建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];
    }
    

    【讨论】:

      【解决方案3】:

      设置按钮的控制状态:

      [btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected];
      [btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
      [btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
      

      【讨论】:

        猜你喜欢
        • 2011-01-29
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        • 2021-02-09
        • 2020-02-04
        • 1970-01-01
        • 2015-02-02
        • 2013-12-16
        相关资源
        最近更新 更多