简体   繁体   English

我可以将一个ivar(或属性)添加到Objective-C中的现有类吗?

[英]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? 我想知道是否可以将ivar添加到UIButton类? A bit like categories but not for a method(s) but for ivars. 有点像类别,但不是针对方法,而是针对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. 我正在以编程方式创建和显示UIButton的数组,然后使用–addTarget:action:forControlEvents:进行–addTarget:action:forControlEvents:全事件,将它们全部链接到单个操作方法。

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). 现在,我的接收器方法需要知道按下了所有按钮中的哪个按钮,但是使用“(id)sender”方法并不会将其剪切掉,因为唯一能区分所有按钮的是图像的显示方式,并且无法获得为此(我需要一个字符串)。 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. 这些按钮都位于不同的位置,因此我可以做一些数学运算以将位置数据转换为“ id”,但是如果我沿行更改按钮的位置,则也需要更改数学运算,但是我不需要像那样。

Can I just subclass UIButton and change nothing except for adding a (NSUInteger)idCode property? 除了添加(NSUInteger)idCode属性,我是否可以(NSUInteger)idCode UIButton并对其进行任何更改? 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 . 然后,当我创建按钮时,设置idCode,并且当target-action机制触发action方法时,我可以执行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? PS:在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. 但这不是必需的-每个UIView (以及包括UIButton子类)都具有您想要的tag属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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