快速按下按钮时填充按钮图标

时间:2018-10-21 11:21:51

标签: ios swift

我有一个带图标的按钮,我希望在按下按钮图标时用颜色填充,然后再次按空颜色并返回到以前的状态

enter image description here

注意:每次按下后,我都不想更改图标。

2 个答案:

答案 0 :(得分:4)

以下是如何实现此目标的示例,如果您不了解某些内容,请告诉我。

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

答案 1 :(得分:1)

您可以调用setImage(_:for:)方法来将按钮的图像设置为特定状态。

当用户不按下按钮时,按钮处于normal状态,因此您应该这样做:

yourButton.setImage(hollowHeart, for: .normal)

当用户触摸按钮时,该按钮处于highlighted状态,因此您应该执行以下操作:

yourButton.setImage(filledHeart, for: .highlighted)

创建按钮后,只需在viewDidLoad中执行一次即可。