首页 > 解决方案 > 按下 UIButton 时如何更改它的颜色?

问题描述

我想知道如何在按下 UIButton 时更改它的颜色。默认情况下,当您按下 UIButton 时,它会变成淡蓝色。当我按下它时,如何将它从褪色变为紫色。我如何在 Swift 4 中做到这一点?我可以更改某种属性吗?

标签: swiftcolorsuibutton

解决方案


斯威夫特 4.2

将此扩展用于按钮:

extension UIButton {
  func setBackgroundColor(_ color: UIColor, forState controlState: UIControl.State) {
    let colorImage = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)).image { _ in
      color.setFill()
      UIBezierPath(rect: CGRect(x: 0, y: 0, width: 1, height: 1)).fill()
    }
    setBackgroundImage(colorImage, for: controlState)
  }
}

简单的用法:

override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton()
        button.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        button.setBackgroundColor(.red, forState: .normal)
        button.setBackgroundColor(.blue, forState: .highlighted)

        view.addSubview(button)
    }

希望这能让你微笑:)


推荐阅读