iOS 7中如何在UIButton被按下时设置标题颜色

31

我在一个视图控制器中有以下代码,所有的outlet和action都已正确连接。 WHITEPURPLE 是我为其定义常量的 UIColor。我还将 UIWindowtintColor 设置为 PURPLE,这会向下传递到按钮。

- (void)viewDidLoad {
    [super viewDidLoad];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    button.backgroundColor = WHITE;
    button.layer.borderWidth = 1.0;
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 5.0;
    button.layer.borderColor = PURPLE.CGColor;
}

-(IBAction) buttonTouchDown:(id)sender {
    button.backgroundColor = PURPLE;
    button.layer.borderColor = WHITE.CGColor;
}

-(IBAction) buttonTouchUpOutside:(id)sender {
    button.backgroundColor = WHITE;
    button.layer.borderColor = PURPLE.CGColor;
}

-(IBAction) buttonTouchUpInside:(id)sender {
    button.backgroundColor = WHITE;
    button.layer.borderColor = PURPLE.CGColor;
}
当我点击按钮时,文本不会变成白色,就像我在viewDidLoad中告诉它的那样。
这里有一些截图,我可以将它们剪裁得更好!正如您在高亮状态中所看到的,它不是白色,而是白色和紫色混合。我需要使用UIButtonTypeCustom吗? 我听说如果这样做,我将无法获得iOS 7与tintColor进行魔术的优势。 不确定正确的方法是什么。提前致谢。 normalState highlightedState

你尝试过使用-setTitleShadowColor吗? - BalestraPatrick
你的问题解答了我的问题。 - Karan Alangat
2个回答

60

你应该使用UIControlStateSelected吗?

好的,我刚刚自己尝试了一下它不能很好地工作。

你需要将按钮样式设置为自定义。UIButton系统样式会执行许多无法更改的操作。高亮按钮状态默认为其自己的实现,这是您的色调颜色的较浅版本。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitleColor:self.view.tintColor forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];

这样做可以让你拥有白色文本背景。


你不应该使用UIControlStateSelected,因为UIButton没有这个状态。 UIControlStateSelected是用于像UISegmentedControl中所选标签之类的东西。 - greenisus
5
请注意,UIButton、UISegmentedControl和其他UIKit类继承自UIControl,该类具有选定状态。无论是Interface Builder还是代码都支持使用UIControlStateSelected UIControlStateDisabled等进行的可视化更改。UIControl的selected属性的好处在于可以从按钮中调用isSelected,并允许按钮处理布尔属性。 - David Wong
3
将按钮样式设置为自定义对我很有效!谢谢! - AXE

-1
希望这是您的问题的答案,或者仍然有人在设置按钮选择时遇到困难。
[btnCustom setTitleColor:[UIColor whiteColor] forState: UIControlStateSelected];
[btnCustom setTitleColor:[UIColor redColor] forState: UIControlStateNormal];

当你想要按钮标题颜色为红色时,将btnCustom.selected设置为NO;如果你想要按钮标题颜色为白色,则将btnCustom.selected设置为YES。

看起来这只是三年前答案的复制。 - Ashley Mills

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