[ios] How to change UIButton image in Swift

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:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];

This question is related to ios xcode swift uibutton

The answer is


Yes, even we can change image of UIButton, by using flag.

class ViewController: UIViewController
{
    @IBOutlet var btnImage: UIButton!
    var flag = false

    override func viewDidLoad()
    {
        super.viewDidLoad()

        //setting default image for button
        setButtonImage()

    }

    @IBAction func btnClick(_ sender: Any)
    {
        flag = !flag
        setButtonImage()
    }

    func setButtonImage(){
        let imgName = flag ? "share" : "image"
        let image1 = UIImage(named: "\(imgName).png")!
        self.btnImage.setImage(image1, for: .normal)
    }

}

Here, after every click your button image will change alternatively.


you can actually do this by highlighting the button and within the insepctor on the right hand tool bar you can update the image. obviously you can do it in code also as stated previously but this is another option for you


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

myButton.setTitle("myTitle", for: [])

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

In Swift 4.2 and Xcode 10.1

Add image for selected UIButton

button.addTarget(self, action: #selector(self.onclickDateCheckMark), for: .touchUpInside)//Target 
button.setImage(UIImage.init(named: "uncheck"), for: UIControl.State.normal)//When selected
button.setImage(UIImage.init(named: "check"), for: UIControl.State.highlighted)//When highlighted
button.setImage(UIImage.init(named: "check"), for: UIControl.State.selected)//When selected

But if you want to change selected button image you need to change it's selected state. Then only selected image will appear in your button.

@objc func onclickDateCheckMark(sender:UIButton) {
    if sender.isSelected == true {
        sender.isSelected = false
        print("not Selected")
    }else {
        sender.isSelected = true
        print("Selected")

    }
}

in swift 3.0:

@IBOutlet weak var selectionButton: UIButton!

selectionButton.setImage(UIImage.addBlueIcon, for: .selected)

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

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

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)

Swift 5

yourButton.setImage(UIImage(named: "BUTTON_FILENAME.png"), for: .normal)

I prefer the method of initializing my variables at the top first:

let playButton:UIButton!
var image:UIImage!

and then setting them in viewDidLoad

override func viewDidLoad {
  ...
  playButton = UIButton(type: .Custom)
  imagePlay = UIImage(named:"play.png")
  playButton.setImage(imagePlay, forState: .Normal)
}

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to xcode

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64 iPhone is not available. Please reconnect the device Make a VStack fill the width of the screen in SwiftUI error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1 Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Xcode 10: A valid provisioning profile for this executable was not found Xcode 10, Command CodeSign failed with a nonzero exit code

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to uibutton

How to make a simple rounded button in Storyboard? How to set the title text color of UIButton? How can I make a button have a rounded border in Swift? How to change UIButton image in Swift Changing text of UIButton programmatically swift Disable a Button How to change font of UIButton with Swift Attach parameter to button.addTarget action in Swift Change button background color using swift language Make a UIButton programmatically in Swift