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.

elke_wtf
  • 887
  • 1
  • 14
  • 30
  • 4
    Why recreate the image instead of just using the same image? `let image = sender.currentImage` – Caleb Aug 12 '15 at 21:45
  • Didn't think of that. Apologies, I'm a new swift developer. This was the correct way to handle it. – elke_wtf Aug 12 '15 at 21:57
  • Possibly Related: https://stackoverflow.com/questions/1740274/uiimageview-how-to-get-the-file-name-of-the-image-assigned/10694684 – Ahmad F Jan 14 '19 at 10:50

2 Answers2

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")
    }
 }
Ram Madhavan
  • 2,362
  • 1
  • 17
  • 20
  • 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 May 08 '20 at 12:40
  • @marika.daboja u can use higher order functions instead if you have multiple images to verify. – Ram Madhavan Jun 23 '20 at 03:58
  • Can you please elaborate - what do you mean by 'higher order functions' ? – marika.daboja Jun 23 '20 at 06:48
6

You can reuse the image using your first line:

let image = sender.currentImage