3

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

    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];

我错过了什么?

4

2 回答 2

2

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

请参阅此处: 为什么我的 UIButton.tintColor 不起作用?

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

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

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

于 2013-01-21T00:00:37.873 回答
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 框架,并将其导入(以使图层属性起作用)。

于 2013-01-21T00:30:50.340 回答