简体   繁体   中英

Fill button icon when button pressed in swift

I have a button with icon, I want when pressed button icon fill with color and when pressed again empty color and return to the previous state

在此处输入图片说明

Note: As much as possible I do not want to change icon after every pressed.

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.

The button is at the normal state when the user is not pressing it, so you should do:

yourButton.setImage(hollowHeart, for: .normal)

The button is at the highlighted state when the user is touching it, so you should do:

yourButton.setImage(filledHeart, for: .highlighted)

You just need to do this once after you create the button, probably in viewDidLoad .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM