向我的所有UIControl添加属性 [英] Adding a property to all of my UIControls

查看:47
本文介绍了向我的所有UIControl添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使应用程序中的每个 UIControl ( UIButton UISlider 等)都具有特殊的额外属性,这些属性我加了他们.

Im trying to make it so that every single UIControl in my application (UIButton, UISlider, etc) all have special extra properties that I add to them.

我试图通过创建 UIControl 类别并将其导入到需要的位置来实现此目的,但是我遇到了问题.

I tried to accomplish this by creating a UIControl Category and importing it where needed but I have issues.

这是我的代码.

我的 setSpecialproperty 方法被调用,但似乎在无限循环中被调用,直到应用程序崩溃.

My setSpecialproperty method gets called but it seems to be getting called in an infinite loop until the app crashes.

您能告诉我我做错了什么吗,还是建议一种更聪明的方法来向我的所有 UIControls 添加属性?

Can you tell me what Im doing wrong or suggest a smarter way to add a property to all of my UIControls?

@interface UIControl (MyControl)
{

}
@property(nonatomic,strong) MySpecialProperty  *specialproperty;

-(void)setSpecialproperty:(MySpecialProperty*)param;
@end

////////

#import "UIControl+MyControl.h"

@implementation UIControl (MyControl)

-(void)setSpecialproperty:(MySpecialProperty*)param
{
    self.specialproperty=param;
}

///////////////

///////////////

#import "UIControl+MyControl.h"

@implementation ViewController


UIButton *abutton=[UIButton buttonWithType:UIButtonTypeCustom];
MySpecialProperty *prop=[MySpecialProperty alloc]init];
[abutton setSpecialproperty:prop];

推荐答案

虽然无法通过类别将iVar添加到UIControl,但是可以添加关联对象",该对象可用于执行几乎相同的功能.

While you can't add an iVar to UIControl via a category, you can add Associated Objects, which can be used to perform much the same function.

因此,像这样在UIControl上创建一个类别:

So, create a category on UIControl like this:

static char kControlNameKey;

- (void) setControlName: (NSString *) name
{
    objc_setAssociatedObject(self, &kControlNameKey, name, OBJC_ASSOCIATION_COPY);
}

- (NSString *) controlName
{
    return (NSString *)objc_getAssociatedObject(array, &kControlNameKey);
}

除此之外,我想您还需要在设置新的关联之前检查某个关联是否存在,否则它将泄漏,但这应该可以助您一臂之力.

There's more to it than that, I guess you'll need to check if an association exists before setting a new one, otherwise it will leak, but this should give you a start.

请参见 Apple Docs 了解更多信息

这篇关于向我的所有UIControl添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆