我想将 UIButton
子类化以添加一些我需要的属性(不是方法...只有属性)。
这里是我的子类的代码:
//.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
是唯一的解决方案吗?
谢谢!
最佳答案
尝试使用 Associative References 的类别反而。它更简洁,适用于 UIButton
的所有实例。
UIButton+Property.h
#import <Foundation/Foundation.h>
@interface UIButton(Property)
@property (nonatomic, retain) NSObject *property;
@end
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);
关于iphone - 子类化 UIButton 添加一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5500327/