How to change button image in swift?

后端 未结 8 2058
一生所求
一生所求 2021-02-10 04:16

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:20

    now (swift 3 edition):

    @IBOutlet var tapButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        tapButton.setImage(UIImage(named: "redTap")?.withRenderingMode(.alwaysOriginal), for: .normal)
        tapButton.setImage(UIImage(named: "redTap")?.withRenderingMode(.alwaysOriginal), for: .normal)
    }
    
    0 讨论(0)
  • 2021-02-10 04:28

    You don't need ".png".

    If ".imageWithRenderingMode(.AlwaysOriginal)" is working for you: To keep the same image in different states, you have to set the same image/properties for the different states.

    @IBOutlet var tapButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        tapButton.setImage(UIImage(named: "redTap")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal)
        tapButton.setImage(UIImage(named: "redTap")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Highlighted)
    }
    
    0 讨论(0)
  • 2021-02-10 04:37

    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

    0 讨论(0)
  • 2021-02-10 04:37
    let button = UIButton(type: .Custom)
    let image = UIImage(named:"redTap")?.imageWithRenderingMode(.AlwaysTemplate)
    button.setImage(image, forState: .Normal)
    button.tintColor = UIColor.redColor()
    
    0 讨论(0)
  • 2021-02-10 04:38

    Swift 3

    yourBtn.setImage( UIImage.init(named: "imagename"), for: .normal)
    
    0 讨论(0)
  • 2021-02-10 04:43

    Let image = UIImage(named : "redTap.png") tapButton.setImage(image, .Normal)

    0 讨论(0)
提交回复
热议问题