【问题标题】:How do I set UIButton background color forState: UIControlState.Highlighted in Swift如何为状态设置 UIButton 背景颜色:UIControl State.Highlighted in Swift
【发布时间】:2014-12-23 10:10:06
【问题描述】:

我可以为按钮设置背景颜色,但我不知道如何为UIControlState.Highlighted 设置背景颜色。甚至可能吗?还是我需要走setBackgroundImage 路径?

【问题讨论】:

标签: ios swift uibutton xcode6


【解决方案1】:

如果有人路过,如果你不止一次需要它,另一种方法可能更容易......我为 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)

【讨论】:

  • 这将破坏自动布局并删除圆角半径。
  • @user4788711 就像设置背景图像一样。不多也不少。
  • 为了修复圆角半径,您只需要在按钮上启用剪辑子视图
  • 对我来说,使用颜色部分的初始化程序扩展 UIImage 是完全值得的。那么这个函数的主体就变成了简单的self.setBackgroundImage(UIImage(color: color), forState: forState)
  • 为什么需要使用graphicContext? button.setBackgroundImage(UIImage(color: .red), for: .normal)一行工作
【解决方案2】:

Swift 3+ 语法

的语法更改为 @winterized extension
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)
    }}

【讨论】:

    【解决方案3】:

    下面将是一种方法。两个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 属性加载所需颜色的图像作为背景图像。

    【讨论】:

    • 该解决方案仅适用于 ViewController,但不适用于 TableViewController。触地动作也适用于 TVC,但只有几毫秒的延迟,因此快速触摸屏幕不会改变按钮的颜色。我认为按钮所在的单元格有问题,但我不确定。
    • 我遇到了完全相同的问题。如果我只点击视图,则不会发生任何事情,因为颜色已经恢复到旧颜色。我可以稍微延迟解决这个问题,以便颜色在几毫秒后切换回来。因此,即使用户只是短暂点击,颜色也是可见的。
    • 另外,我认为“Touch Down”方法是有风险的。首先,它不会自动重置颜色。这很容易,在“Touch-up Inside”上只需将其设置回原始颜色即可。但是如果用户做了一些不正常的事情,比如按下去,然后决定不继续,然后拖开手指怎么办。颜色不会重置。
    【解决方案4】:

    已接受答案的 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
    【解决方案5】:

    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 的功能
    【解决方案6】:

    这里似乎没有人提到使用 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
    

    【讨论】:

      【解决方案7】:

      更新 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)
          }
      

      事件 按钮动作

      高亮显示触摸

      【讨论】:

        【解决方案8】:

        为什么不呢?

        @implementation UIButton (Color)
        
        - (void) setBackgroundColor:(UIColor*)color forState:(UIControlState)state
        {
            [self setBackgroundImage:[UIImage.alloc initWithCIImage:[CIImage imageWithColor:[CIColor colorWithCGColor:color.CGColor]]] forState:state];
        }
        
        @end
        

        【讨论】:

        • 我试过这个,但我必须裁剪图像,例如宽度:1,高度:1 以使其工作。由于 imageWithColor 产生的无限范围,它不起作用。
        【解决方案9】:

        在 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
        
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-29
          • 2016-11-06
          • 1970-01-01
          • 2011-06-13
          • 2019-03-01
          • 2020-01-26
          相关资源
          最近更新 更多