子类UIButton添加属性 [英] Subclass UIButton to add a property

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

问题描述

我想继承 UIButton 来添加我需要的一些属性(不是方法...只有属性)。

I'd like to subclass UIButton to add some properties that i need (not methods... only properties).

这里是我的子类的代码:

Here the code of my subclass:

//.h-----------------------
@interface MyButton : UIButton{
    MyPropertyType *property;
}

@property (nonatomic,retain) MyPropertyType *property;
@end

//.m--------------------------
@implementation MyButton
@synthesize property;

@end

这里我如何使用该类:

MyButton *btn = ((MytButton *)[MyButton buttonWithType:UIButtonTypeRoundedRect]);
btn.property = SomeDataForTheProperty;

我从哪里获得此错误:

 -[UIRoundedRectButton setProperty:]: unrecognized selector sent to instance 0x593e920

因此,从 ButtonWithType 我获得 UIRoundedRectButton (Mybutton *)无法投射...
我需要做什么才能获得 MyButton 对象?是 -init 独特的解决方案?

Thus, from ButtonWithType i obtain a UIRoundedRectButton and (Mybutton *) can't cast it... What i have to do to obtain a MyButton object ? is -init the unique solution ?

谢谢!

推荐答案

尝试使用关联引用。它更干净,适用于 UIButton 的所有实例。

Try using a category with Associative References instead. It is much cleaner and will work on all instances of UIButton.

UIButton + Property.h

UIButton+Property.h

#import <Foundation/Foundation.h>

@interface UIButton(Property)

@property (nonatomic, retain) NSObject *property;

@end

UIButton + Property.m

UIButton+Property.m

#import "UIButton+Property.h"
#import <objc/runtime.h>

@implementation UIButton(Property)

static char UIB_PROPERTY_KEY;

@dynamic property;

-(void)setProperty:(NSObject *)property
{
    objc_setAssociatedObject(self, &UIB_PROPERTY_KEY, property, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSObject*)property
{
    return (NSObject*)objc_getAssociatedObject(self, &UIB_PROPERTY_KEY);
}

@end

//使用示例

#import "UIButton+Property.h"

...

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button1.property = @"HELLO";
NSLog(@"Property %@", button1.property);
button1.property = nil;
NSLog(@"Property %@", button1.property);

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

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