How to change button image in swift?

后端 未结 8 852
陌清茗
陌清茗 2021-02-10 04:09

I am working on an app which has a button. The button has no text, image or background.

So what I want to do is to give it an image in the viewDidLoad function.

8条回答
  •  南笙
    南笙 (楼主)
    2021-02-10 04:21

    First set your button type as Custom in interface builder and set the image for normal state for your button.

    Connect IBOutlet for button in class file as

    @IBOutlet weak var btnCheckbox: UIButton!
    

    in your class file in viewDidLoad set image for selected state as

    btnCheckbox.setImage(UIImage.init(named: "name_of_image"), for: .selected)
    

    Create @IBAction for in class file as

    @IBAction func onTapCheckBox(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    

    Then connect @IBAction to your button's Touch up Inside event from interface builder

提交回复
热议问题