Wun
Wun

Reputation: 6381

How to get the image name of button in IOS?

I am new to IOS and Objective-C.

I set the image to the button like the following code.

UIButton *modeChangeButton = [[UIButton alloc] initWithFrame:CGRectMake(233, 490, 60, 60)];
[modeChangeButton setImage:[UIImage imageNamed:@"recordmode.PNG"] forState:UIControlStateNormal];

[self.view addSubview:modeChangeButton];

But how to get the image name of the button ?

For example, I want to get the recordmode.PNG...

Thanks in advance.

Upvotes: 0

Views: 2791

Answers (4)

Alexander
Alexander

Reputation: 101

Get the name of the UIImage in iOS,this is working!

example:

let sender = UIButton(type: .custom)
sender.setImage(UIImage(named: "Item_center_H"), for: .normal)

if let image = sender.image(for: .normal) {
   DDLog(image.assetName)  // Item_center_H

}

code:

@objc public extension UIImage{

    var assetName: String? {
        guard let imageAsset = imageAsset else { return nil }
        return imageAsset.value(forKey:"assetName") as? String
    }
}

Upvotes: 0

Ramdhas
Ramdhas

Reputation: 1765

You can't. UIImage does not store the name of the image it contains. You have to store the name elsewhere by yourself in relationship to the Button or image.

Upvotes: 3

Ravi
Ravi

Reputation: 2451

First Store Your Image Name in a String like

NSString * imageNameString = @"yourImageName.png";

and then

UIButton *modeChangeButton = [[UIButton alloc] initWithFrame:CGRectMake(233, 490, 60, 60)];
[modeChangeButton setImage:[UIImage imageNamed:imageNameString] forState:UIControlStateNormal];

[self.view addSubview:modeChangeButton];

if you want your button image name simply use imageNameString

Upvotes: 0

Suyog Patil
Suyog Patil

Reputation: 1616

To set the image name use below code:

[Your_Button setAccessibilityIdentifier:[NSString stringWithFormat:@"%@",imageName]];

Where imageName=@"recordmode.PNG";

And to get the image name

[Your_Button accessibilityIdentifier];

Upvotes: 3

Related Questions