【发布时间】:2014-12-23 10:10:06
【问题描述】:
我可以为按钮设置背景颜色,但我不知道如何为UIControlState.Highlighted 设置背景颜色。甚至可能吗?还是我需要走setBackgroundImage 路径?
【问题讨论】:
-
查看帖子末尾的somethingaboutios.wordpress.com/2016/02/09/… Swift 示例。
我可以为按钮设置背景颜色,但我不知道如何为UIControlState.Highlighted 设置背景颜色。甚至可能吗?还是我需要走setBackgroundImage 路径?
【问题讨论】:
如果有人路过,如果你不止一次需要它,另一种方法可能更容易......我为 UIButton 写了一个简短的扩展,它工作得很好:
对于 Swift 3
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, forState: forState)
}
}
对于 Swift 4
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControl.State) {
self.clipsToBounds = true // add this to maintain corner radius
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
}
}
你就像setBackgroundImage一样使用它:
yourButton.setBackgroundColor(color: UIColor.white, forState: UIControl.State.highlighted)
【讨论】:
self.setBackgroundImage(UIImage(color: color), forState: forState)
button.setBackgroundImage(UIImage(color: .red), for: .normal)一行工作
Swift 3+ 语法
的语法更改为 @winterized extensionextension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}}
【讨论】:
下面将是一种方法。两个IBAction。一种在按下按钮时控制背景颜色,一种在释放时控制。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
@IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action
button.backgroundColor = UIColor.whiteColor()
}
@IBAction func buttonReleased(sender: AnyObject) { //Touch Down action
button.backgroundColor = UIColor.blueColor()
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
当您在添加句点后查看按钮的自动完成选项时,您可以设置背景颜色,但不能设置指定状态。您只能设置背景图像。当然,如果您愿意采用这种方式而不是使用我上面展示的方法,您可以使用 setbackgroundImageForState 属性加载所需颜色的图像作为背景图像。
【讨论】:
已接受答案的 Swift 4+ 兼容性:
extension UIButton {
/// Sets the background color to use for the specified button state.
func setBackgroundColor(color: UIColor, forState: UIControlState) {
let minimumSize: CGSize = CGSize(width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(minimumSize)
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(CGRect(origin: .zero, size: minimumSize))
}
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.clipsToBounds = true
self.setBackgroundImage(colorImage, for: forState)
}
}
兼容 SwiftLint 并修复自动布局/角半径损坏的错误。
【讨论】:
system 而不是custom
Swift 4 版本的this solution:
extension UIButton {
func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
setBackgroundImage(colorImage, for: state)
}
}
【讨论】:
if let currentGraphicsContext = UIGraphicsGetCurrentContext() { currentGraphicsContext.setFillColor(color.cgColor) currentGraphicsContext.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) } 加上 layer.masksToBounds = true 以保持 layer.cornerRadius 的功能
这里似乎没有人提到使用 Key Value Observation,但这是另一种方法。
这样做而不是在这里选择其他答案的原因是您不需要一直创建新图像,也不需要担心将图像分配给按钮的次要效果(例如cornerRadius 效果)。
但您需要为观察者创建一个类,该类负责存储不同的背景颜色并将它们应用到observeValue() 方法中。
public class ButtonHighlighterObserver: NSObject {
var observedButton:UIButton? = nil
var backgroundColor: UIColor = UIColor.white
var backgroundHighlightColor: UIColor = UIColor.gray
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// Perform background color changes when highlight state change is observed
if keyPath == "highlighted", object as? UIButton === observedButton {
observedButton!.backgroundColor = observedButton!.isHighlighted ? self.backgroundHighlightColor : self.backgroundColor
}
}
}
那么你需要做的就是在操作过程中管理addObserver / removeObserver:
// Add observer to button's highlighted value
button.addObserver(anObserver, forKeyPath: "highlighted", options: [.new], context: nil)
anObserver.observedButton = button
// ...
// And at deinit time, be sure you remove the observer again
anObserver.observedButton?.removeObserver(item, forKeyPath: "highlighted")
anObserver.observedButton = nil
【讨论】:
更新 Swift 4
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
事件 按钮动作
高亮显示触摸
【讨论】:
为什么不呢?
@implementation UIButton (Color)
- (void) setBackgroundColor:(UIColor*)color forState:(UIControlState)state
{
[self setBackgroundImage:[UIImage.alloc initWithCIImage:[CIImage imageWithColor:[CIColor colorWithCGColor:color.CGColor]]] forState:state];
}
@end
【讨论】:
在 Swift 5 中
对于那些不想使用彩色背景来击败选定状态的人
您可以通过使用#Selector & if 语句轻松地单独更改每个状态的 UIButton 颜色来解决问题
例如:
override func viewDidLoad() {
super.viewDidLoad()
//to reset the button color to its original color ( optionally )
self.myButtonOutlet.backgroundColor = UIColor.white
}
@IBOutlet weak var myButtonOutlet: UIButton!{
didSet{ // Button selector and image here
self.myButtonOutlet.setImage(UIImage(systemName: ""), for: UIControl.State.normal)
self.myButtonOutlet.setImage(UIImage(systemName: "checkmark"), for: UIControl.State.selected)
self.myButtonOutlet.addTarget(self, action: #selector(tappedButton), for: UIControl.Event.touchUpInside)
}
}
@objc func tappedButton() { // Colors selection is here
if self.myButtonOutlet.isSelected == true {
self.myButtonOutlet.isSelected = false
self.myButtonOutlet.backgroundColor = UIColor.white
} else {
self.myButtonOutlet.isSelected = true
self.myButtonOutlet.backgroundColor = UIColor.black
self.myButtonOutlet.tintColor00 = UIColor.white
}
}
【讨论】: