[英]Fill button icon when button pressed in swift
Here is example how you can achieve that, let me know if you don't understand something. 这是您如何实现此目标的示例,如果您不了解某些内容,请告诉我。
class ViewController: UIViewController {
@IBOutlet weak var someBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
//Setting up images for normal and selected state.
func configureUI() {
let image = UIImage(named: "image")
let imageFilled = UIImage(named: "image-filled")
someBtn.setImage(image, for: .normal)
someBtn.setImage(imageFilled, for: .selected)
}
@IBAction func someBtnPressed(_ sender: Any) {
// Toggle basically makes someBtn’s selected state either true or false when pressed
someBtn.isSelected.toggle()
}
}
You can call setImage(_:for:)
method to set the image of the button for a particular state. 您可以调用setImage(_:for:)
方法来为特定状态设置按钮的图像。
The button is at the normal
state when the user is not pressing it, so you should do: 当用户不按该按钮时,该按钮处于normal
状态,因此您应该执行以下操作:
yourButton.setImage(hollowHeart, for: .normal)
The button is at the highlighted
state when the user is touching it, so you should do: 当用户触摸按钮时,该按钮处于highlighted
状态,因此您应该执行以下操作:
yourButton.setImage(filledHeart, for: .highlighted)
You just need to do this once after you create the button, probably in viewDidLoad
. 创建按钮后,只需在viewDidLoad
执行一次即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.