简体   繁体   中英

can i add an ivar (or property) to an existing class in objective-c?

I'm wondering if it's possible to add an ivar to the UIButton class? A bit like categories but not for a method(s) but for ivars.

I am programmatically creating and displaying an array of UIButton's which I then all link up to a single action method using –addTarget:action:forControlEvents: for a touchup event.

Now, my receiver method needs to know which of all the buttons was pressed but using the "(id)sender" approach doesn't cut it because the only thing differentiating all the buttons is the image its displaying and there is no way to get to that (I need a string). The buttons are all in different places so I could do some math to convert the position data into an "id" but if I change the positioning of the buttons down the line, I will need to change the math as well and I don't like that.

Can I just subclass UIButton and change nothing except for adding a (NSUInteger)idCode property? Then when I create the buttons I set the idCode, and when the target-action mechanism fires the action method, I can just do sender.idCode . Is this the way to do it?

Is there a better standard/elegant way of implementing this kind of multiple target-action see-where-it-came-from behaviour?

PS: Is there a quick way to type the backtick on a Mac?

You could do it this way. But this is not necessary - every UIView (and subclasses which includes UIButton ) has the tag property which is just what you want.

UIButton以及所有UIView子类已经具有用于该目的的integer属性: tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM