【问题标题】:UIButton color issuesUIButton颜色问题
【发布时间】:2011-06-22 00:45:57
【问题描述】:

如何更改 UIButton 上文本的颜色。这是我当前的代码:

    UIButton *b1 = [[UIButton alloc] init];
    b1.frame = CGRectMake(280,395,30,30);
    [[b1 layer] setCornerRadius:8.0f];
    [[b1 layer] setMasksToBounds:YES];
    [[b1 layer] setBorderWidth:1.0f];
    [[b1 layer] setBackgroundColor:[botCol CGColor]];
    b1.titleLabel.font = [UIFont boldSystemFontOfSize:24];
    [b1 setTitleColor:[UIColor redColor] forState:UIControlEventAllEvents];
    [b1 addTarget:self action:@selector(NextButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [b1 setTitle:@">" forState:UIControlStateNormal];
    [self.view addSubview:b1];

这是它的样子(忽略背景颜色和其他东西):

现在,我怎样才能让箭头变成红色?正如你在上面看到的,我已经有了以下内容:

[b1 setTitleColor:[UIColor redColor] forState:UIControlEventAllEvents];

但它不起作用。

【问题讨论】:

    标签: iphone ios uibutton


    【解决方案1】:

    尝试设置个别事件,例如:

    [b1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    

    【讨论】:

    • 现在如果我希望在用户触摸按钮时背景为白色怎么办?代码会是什么样子?
    • @reising:我认为你不能通过事件触发它。我能想到的唯一解决方法是将其添加到代码中触发的操作中(NextButtonPressed)。 [[b1 layer] setBackgroundColor:[UIColor greenColor].CGColor]; 但是,您必须将 b1 设为实例变量才能在原始方法之外访问它。
    【解决方案2】:

    您的原始代码无法正常工作的原因是因为您传入的是 UIControlEvents 参数而不是 UIControlState 参数。

    [b1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    

    这将为正常状态设置颜色,除非您为其他状态设置颜色,否则它将在所有状态中持续存在。要更改其他状态的颜色,只需对其他状态调用相同的方法(UIControlStateNormalUIControlStateHighlightedUIControlStateDisabledUIControlStateSelected):

    [b1 setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-05
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 2018-01-22
      相关资源
      最近更新 更多