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" a开发者_如何学Cpproach 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?
P.S.: 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 as well as all UIView subclasses already has an integer property for exactly that purpose: tag
精彩评论