Swift 设置按钮图片

Swift set button image

当我尝试在按下按钮时更改按钮的图像,但它只显示一个蓝色方块作为按钮的图像

@IBAction func button(_ sender: Any) {
     buttonOutlet.setImage(#imageLiteral(resourceName: "thing"), for: UIControl.State.normal)
}

只需重新检查您的目标中是否有 "thing" - 图片。

button.setImage(UIImage(named: "thing"), for: [.selected, .highlighted])

然后看到这个问题 UIButton: set image for selected-highlighted state

来自 Apple 文档:

A control becomes highlighted when a touch event enters the control’s bounds...

Highlighted state of a control

button.setImage(UIImage(named: "button_normal_state"), for: .normal)
button.setImage(UIImage(named: "button_pressed_state"), for: .highlighted)