5

Currently have a button with an embedded image. I'd like to get the image name of the button so that I can create a UIImage with it for sharing when the user clicks the button.

I've tried a variety of methods including

let imagename = sender.currentImage
let image = UIImage(name: imagename)

This results in error "Missing argument for parameter 'inBundle' in call

Looking for some guidance on how to proceed. I am going to have many buttons similar to this one and would rather build a function than individual actions for each button.

3
  • 4
    Why recreate the image instead of just using the same image? let image = sender.currentImage Commented Aug 12, 2015 at 21:45
  • Didn't think of that. Apologies, I'm a new swift developer. This was the correct way to handle it. Commented Aug 12, 2015 at 21:57
  • Possibly Related: stackoverflow.com/questions/1740274/… Commented Jan 14, 2019 at 10:50

2 Answers 2

14

Get the image name you have assigned to your UIButton:

let createdButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
createdButton.setImage(UIImage(named: "Image_Assigned"), for: .normal)
checkButtonName(yourButton: createdButton)

func checkButtonName(yourButton: UIButton) {
    if yourButton.currentImage == UIImage(named: "Image_Assigned") {
       print("IMAGE NAME IS Image_Assigned")
    }
    else {
       print("IMAGE NAME IS NOT Image_Assigned")
    }
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for sharing this solution, but I'm wondering is there anything shorter available? In my case I have over 30 images to compare with hence IF statement is really long. Surely there must be a better way of handling it??
@marika.daboja u can use higher order functions instead if you have multiple images to verify.
Can you please elaborate - what do you mean by 'higher order functions' ?
6

You can reuse the image using your first line:

let image = sender.currentImage

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.