How to change UIButton image in Swift

前端 未结 12 1297
猫巷女王i
猫巷女王i 2020-12-01 00:25

I am trying to change the image of a UIButton using Swift... What should I do

This is OBJ-C code.but I don\'t know with Swift:

[playButton setImage:[         


        
相关标签:
12条回答
  • 2020-12-01 00:52

    For anyone using Assets.xcassets and Swift 3, it'd be like this (no need for .png)

    let buttonDone  = UIButton(type: .Custom)
    
    if let image = UIImage(named: "Done") {
        self.buttonDone.setImage(image, for: .normal)
    }
    
    0 讨论(0)
  • 2020-12-01 00:52

    As of swift 3.0 .normal state has been removed.you can use following to apply normal state.

    myButton.setTitle("myTitle", for: [])
    
    0 讨论(0)
  • 2020-12-01 00:56

    assume that this is your connected UIButton Name like

    @IBOutlet var btn_refresh: UIButton!
    

    your can directly place your image in three modes

     // for normal state
    btn_refresh.setImage(UIImage(named: "xxx.png"), forState: UIControlState.Normal)
         // for Highlighted state
          btn_refresh.setImage(UIImage(named: "yyy.png"), forState: UIControlState.Highlighted)
    
            // for Selected state
             btn_refresh.setImage(UIImage(named: "zzzz.png"), forState: UIControlState.Selected)
    

    on your button action

      //MARK: button_refresh action
    @IBAction func button_refresh_touchup_inside(sender: UIButton)
    {
        //if you set the image on same  UIButton
        sender.setImage(UIImage(named: "newimage.png"), forState: UIControlState.Normal)
    
        //if you set the image on another  UIButton
           youranotherbuttonName.setImage(UIImage(named: "newimage.png"), forState: UIControlState.Normal)
    }
    
    0 讨论(0)
  • 2020-12-01 01:01

    in Swift 4, (Xcode 9) example to turn picture of button to On or Off (btnRec):

    var bRec:Bool = true
    
    @IBOutlet weak var btnRec: UIButton!
    @IBAction func btnRec(_ sender: Any) {
        bRec = !bRec
        if bRec {
            btnRec.setImage(UIImage(named: "MicOn.png"), for: .normal)
        } else {
            btnRec.setImage(UIImage(named: "MicOff.png"), for: .normal)
        }
    }
    
    0 讨论(0)
  • 2020-12-01 01:01

    in swift 3.0:

    @IBOutlet weak var selectionButton: UIButton!
    
    selectionButton.setImage(UIImage.addBlueIcon, for: .selected)
    
    0 讨论(0)
  • 2020-12-01 01:05

    Swift 5 and ensures the image scales to the size of the button but stays within the buttons bounds.

    yourButton.clipsToBounds = true
    yourButton.contentMode = .scaleAspectFill
    
    // Use setBackgroundImage or setImage
    yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)
    
    0 讨论(0)
提交回复
热议问题