iphone - 子类化 UIButton 添加一个属性

标签 iphone objective-c ios uibutton

我想将 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/

相关文章:

iphone - 属性与实例变量

ios - 延时播放音频文件

ios - SDWebImage 是否同时使用内存缓存和磁盘缓存(需要时)?如果不是,我该如何处理?

iOS 7 : Blank Screen when presenting MFMailComposeViewController on navigationController

iphone - 在我的主 tableView 中添加 Facebook Like 按钮?

ios - 在 iphone X 的安全区域设置 Webview

iphone - 当条件变为真时禁用后退按钮对 ios 来说是一种良好的用户体验吗?

ios - 如何通知 UITableViewController 来自 UITableViewCell 子类的事件?

ios - 将 iPad 应用更新为通用应用

iphone - NSDate - 一年前,困境