UIButton仅在按下时显示tintColor,而不是正常状态

时间:2013-01-20 23:48:29

标签: ios objective-c colors

这是我的代码。它会创建一个白色按钮,按下时会变为紫色。我想要的是紫色按钮。

    if (!backButton) {
    backButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [backButton setTitle:@"Back" forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:17];
    CGSize size = [aboutButton.titleLabel.text sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:23]];
    backButton.frame = CGRectMake(screenWidth/2 - size.width/2, screenHeight-size.height*4, size.width, size.height);
    backButton.tintColor = [UIColor colorWithRed:123/255.0 green:47/255.0 blue:85/255.0 alpha:1]; //This is the color I want the button to be in its normal state.
    [backButton addTarget:self action:NSSelectorFromString(@"displaySettingsScreen") forControlEvents:UIControlEventTouchUpInside];
}
[self.view addSubview:backButton];

我错过了什么?

2 个答案:

答案 0 :(得分:2)

可悲的是,tintColor属性不适用于RoundedRect按钮类型。

见这里: Why is my UIButton.tintColor not working?

为了解决这个问题,我使用单段UISementedControl来代替我想要的UIButton。

这里的答案描述了这种技术: https://stackoverflow.com/a/4971371/785411

另一种选择是使用紫色图像作为按钮 - 虽然这需要更多的工作。

答案 1 :(得分:1)

圆角矩形按钮很难更改,因此请改用自定义按钮,然后设置背景颜色:

if (!backButton) {
        backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setTitle:@"Back" forState:UIControlStateNormal];
        backButton.titleLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:17];
        CGSize size = [aboutButton.titleLabel.text sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:23]];
        backButton.frame = CGRectMake(screenWidth/2 - size.width/2, screenHeight-size.height*4, size.width, size.height);
        backButton.layer.cornerRadius = 6.0f;
        backButton.backgroundColor = [UIColor colorWithRed:123/255.0 green:47/255.0 blue:85/255.0 alpha:1]; //This is the color I want the button to be in its normal state.
        [backButton addTarget:self action:NSSelectorFromString(@"displaySettingsScreen") forControlEvents:UIControlEventTouchUpInside];
    }
    [self.view addSubview:backButton];

您需要添加QuartzCore框架并导入它(使图层属性起作用)。