在iOS中点击按钮时更改按钮文本颜色

3

我知道这个问题经常被问到,也有很多正确的答案,但我在我的代码中遇到了一个问题。我有一些单选按钮,当用户点击按钮时,背景颜色和文本颜色会改变。背景颜色改变得如我所预期,但是文本颜色在按钮被点击时变成了蓝色区域。我已经编写了代码,在点击时将其更改为白色,但是当我点击按钮时,它会将文本区域改为蓝色,我不知道我犯了什么错误。我的代码如下:

 self.selectedTitleColor = [UIColor whiteColor];
self.selectedBackgroundColor = [UIColor redColor];

self.unselectedTitleColor = [UIColor blackColor];
self.unselectedBackgroundColor = [UIColor whiteColor];

- (IBAction)House:(id)sender {

[sender setSelected: ![sender isSelected]];
[self.flat setSelected:NO];
[self.lowerP setSelected:NO];
[self.upperP setSelected:NO];
[self.farmH setSelected:NO];
[self.pentH setSelected:NO];
[self.roomB setSelected:NO];


[self updateButtonColors];

}

-(void)updateButtonColors {
if (self.house.selected) {
    [self.house setTitleColor:self.selectedTitleColor forState:UIControlStateNormal];
    [self.house setBackgroundColor:self.selectedBackgroundColor];

    House=_house.titleLabel.text;
    ImageViewD = [NSString stringWithFormat:@"%@",House];

    NSLog(@"HHHH  %@",ImageViewD);

} else {
    [self.house setTitleColor:self.unselectedTitleColor forState:UIControlStateNormal];
    [self.house setBackgroundColor:self.unselectedBackgroundColor];
        }

}

enter image description here

2个回答

2

在Storyboard中将按钮类型从系统更改为自定义

enter image description here


非常感谢。@KKRocks - Hamza Imran

0
最好将所有属性放入Storyboard中。您可以为颜色选择两个图像,并将其设置为UIButton的backgroundImage状态。
请查看下面的图片。
[Normal State]

Selected State

我有一个绑定了以下方法及其代码的按钮:

- (IBAction)clicked:(id)sender {
    UIButton *btn = (UIButton *)sender;
    btn.selected = !btn.selected;
}

以下是我拍摄的参考图片。

Red.png

Green.png

希望它能对你有所帮助。

我没听懂,你能再解释一下吗?@Nirmalsinh - Hamza Imran
您需要拍摄两张纯色图像。我拍了一张红色和一张绿色的图像,以便为特定状态进行更改。同时设置我们想要的文本颜色。 - Nirmalsinh Rathod
当按钮被点击时,它会如何改变颜色? - Hamza Imran
我在更新的答案中添加了红色和绿色的PNG文件。您可以选择任何您喜欢的颜色。 - Nirmalsinh Rathod
兄弟,我不知道如何同时将两个图像添加到背景中?@Nirmalsinh - Hamza Imran
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接