gersonmontenegro gersonmontenegro - 2 months ago 32
Swift Question

How to get the custom image name in a UIBarButtonItem button in Swift 3?

I have this method in a custom class:

func changeImage(btn:UIBarButtonItem, imageName: String){
btn.image = UIImage(named: imageName)
}


I would like write another method that can give me the same name passed in the 'imageName' parameter...something like:

func getImageName(btn:UIBarButtonItem) -> String{
return btn.image.someVarOrMethodWithImageName
}


I try some of properties and subProperties like

btn.image?.accessibilityIdentifier
btn.image?.imageAsset.debugDescription
btn.image?.imageAsset?.value(forKey: "named")


And others, but none of them are working.

Lot of thanks!

Answer

Basically what you can do is subclass UIBarButtonItem and declare a property as var imageName: String? and when you assign the image to your UIBarButtonItem, assign this imageName with actual value. So that you can access it later anywhere(unless it is your custom 'UIBarButtonItem' class).

For example:

class MyBarButtonItem: UIBarButtonItem {
    var imageName: String?
}

//....
func changeImage(btn: MyBarButtonItem, imageName: String){
    btn.image = UIImage(named: imageName)
    btn.imageName = imageName
}

func getImageName(btn: MyBarButtonItem) -> String? {
    return btn.imageName
}