Bluewings
Bluewings

Reputation: 3488

How to get the background image name of a button by sub classing UIButton?

I want to get the background image name of the button when taping it. After searching a lot in internet i found that

Since UIImage does not store the name of the image it contains, . We have to store the name elsewhere by yourself in relationship to the Button or image

via this SO answer. However i want to know how to get the background image name of button by sub classing UIButton? What method i need to over ride from UIButton to get the background image name?

Button's tag,Title text and accessibilityIdentifier am using already for other purpose. So i left with no option other than getting the image name.

My app supports from iOS 7 to latest.

Upvotes: 1

Views: 2077

Answers (2)

matt
matt

Reputation: 625

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

How to get the name of the backgroundImage from a button?

Upvotes: 1

ZeMoon
ZeMoon

Reputation: 20274

You can store the image name within an instance of UIImage itself by using a category.

Add a new category on UIImage called ImageName and add a property to it:

//UIImage+ImageName.h

#import <UIKit/UIKit.h>

@interface UIImage (ImageName)

@property (strong, nonatomic) NSString *imgName;

@end

Then, you can simply attach the name of the image to any UIImage by importing the category.

#import "UIImage+ImageName.h"

NSString *name = @"someImage.jpg";
UIImage *image = [UIImage imageNamed:name];
image.imgName = name;

Upvotes: 4

Related Questions