按下按钮时如何更改UIButton的颜色?

时间:2019-02-24 03:42:25

标签: swift colors uibutton

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

5 个答案:

答案 0 :(得分:1)

使用setTitleColor(_:for:).normal.highlighted状态(第二个参数)设置标题颜色(第一个参数)。

请参见https://developer.apple.com/documentation/uikit/uibutton/1623993-settitlecolor

答案 1 :(得分:1)

Swift 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)
    }

希望这会让你微笑:)

答案 2 :(得分:0)

我认为您可以使用sonar-scala_2.12-7.3.1-assembly.jar函数对其进行存档:

setBackgroundImage

您可以为button.setBackgroundImage(UIImage(named: "PURPLE_IMAGE"), for: .highlighted) highlightedselected ...等设置图像

我知道您的问题是要更改突出显示的背景颜色,而不是背景图像,但不幸的是,它似乎没有直接的方法。因此,我的解决方法是以编程方式创建具有相同效果的该颜色的图像(您可能希望将其放在UIImage扩展中):

disable

答案 3 :(得分:0)

如果您想通过单击来更改UIButton的背景颜色,只需使用backgroundColor属性,如下所示:

@IBAction func btnTapped(_ sender: UIButton) { //sender type should be UIButton
    sender.backgroundColor = UIColor.purple
}

,如果要在单击时设置标题颜色,可以使用setTitleColor属性,如下所示:

@IBAction func btnTapped(_ sender: UIButton) {
    sender.setTitleColor(UIColor.purple, for: .highlighted)
}

答案 4 :(得分:0)

使用.backgroundColor设置颜色; var button_isActive用于按下按钮,UIView.animate

 var button_isActive: Bool = false 

 @IBAction func btn_Button(_ sender: UIButton) {
    if button_isActive {
        UIView.animate(withDuration: 0.2) {
            sender.backgroundColor = UIColor.clear
        }
    } else {
        UIView.animate(withDuration: 0.2) {
            sender.backgroundColor = UIColor.purple
        }
    }
    button_isActive = !button_isActive
}