IOS/Swift: check for button image to toggle button image

1704 views ios
-1

I am just learning Swift and am trying to toggle a button based on a user action between two images. It would be nice to just check the name of the images showing and toggle to the other one.

I am able to get the image from the button but not necessarily it's name. My question is how to compare it to the image name in Swift.

func toggleImage(){
        var img = self.sendButton.image(for: .normal)//NO ERROR
        if img.isEqual(image-one) {//ERROR HERE
      //switch to image-two
        }
else {
//switch to image-one
    }
}

Thanks in advance for any suggestions.

answered question

You chose very hard way of achieving what you want. Consider using different images for different states of UIButton, like selected and normal. This way, when tapped you can switch selected property of the button to true or false, and image will change.

3 Answers

9

You need to get image name and compare it like below

  if self.sendButton.currentImage == UIImage(named: "image-one") {
           //switch to image-two
            }else {
    //switch to image-one
        }

posted this
4

  1. Using ===

    private let image-one = UIImage(named: "name1") private let image-two = UIImage(named: "name2") override func viewDidLoad() { sendButton.setImage(image-one, for: .normal) }
    func toggle image() { if self.sendButton.currentImage === image-one { ..... } }

  2. Using flags (less elegant, but much safer):

    enum WhichImage { case image-one, image-two } private var whichImage: WhichImage = .image-one

Instead of checking images you check whichImage and update it when image is changed.

posted this
9

There is a better way. Treat the button like a checkbox. The unchecked state is image 1, the checked state is image 2.

To setup a UIButton to work like a checkbox, use the isSelected property.

sendButton.setImage(UIImage(named: "image1"), for: .normal)
sendButton.setImage(UIImage(named: "image2"), for: .selected)

// You may also need to set the image for the highlighted selected state.
sendButton.setImage(UIImage(named: "image2"), for: [.selected, .highlighted])

Now that the button knows about both images, you can switch between the to using the isSelected property.

func toggleImage() {
    sendButton.isSelected = !sendButton.isSelected
}

posted this

Have an answer?

JD

Please login first before posting an answer.