How to change the background color of a UIButton while it#39;s highlighted?(突出显示时如何更改 UIButton 的背景颜色?)
问题描述
在我的应用程序中的某个时刻,我有一个突出显示的 UIButton
(例如,当用户将手指放在按钮上时)并且我需要在按钮突出显示时更改背景颜色(所以当用户的手指仍在按钮上).
At some point in my app I have a highlighted UIButton
(for example when a user has his finger on the button) and I need to change the background color while the button is highlighted (so while the finger of the user is still on the button).
我尝试了以下方法:
_button.backgroundColor = [UIColor redColor];
但它不起作用.颜色保持不变.当按钮未突出显示并且工作正常时,我尝试了相同的代码.我也试过在改变颜色后调用-setNeedsDisplay
,没有任何效果.
But it is not working. The color remains the same. I tried the same piece of code when the button is not highlighted and it works fine. I also tried calling -setNeedsDisplay
after changing the color, it didn't have any effect.
如何强制按钮改变背景颜色?
How to force the button to change the background color?
推荐答案
你可以重写UIButton
的setHighlighted
方法.
Objective-C
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
if (highlighted) {
self.backgroundColor = UIColorFromRGB(0x387038);
} else {
self.backgroundColor = UIColorFromRGB(0x5bb75b);
}
}
Swift 3.0 和 Swift 4.1
override open var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? UIColor.black : UIColor.white
}
}
这篇关于突出显示时如何更改 UIButton 的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:突出显示时如何更改 UIButton 的背景颜色?


- URL编码Swift iOS 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- UITextView 内容插图 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01