我想继承 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
这里是我如何使用这个类:
And here how I use the class:
MyButton *btn = ((MytButton *)[MyButton buttonWithType:UIButtonTypeRoundedRect]);
btn.property = SomeDataForTheProperty;
我从哪里得到这个错误:
From where i obtain this error :
-[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 添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!