我有一个自定义按钮类:
CustomButton.h 文件:
@interface CustomButton : UIButton
@property (nonatomic, retain) NSString* info;
@end
CustomButton.m 文件:
#import "CustomButton.h"
@implementation CustomButton
@synthesize info;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
@end
在我的主视图 Controller 中:
CustomButton* btn = [CustomButton buttonWithType:UIButtonTypeDetailDisclosure];
[btn setInfo:@"foobar"];
NSLog(@"%@", [btn info]);
[self.view addSubview:btn];
如果它只是一个简单的按钮 ([CustomButton new]
),我不会收到任何错误。但是如果我选择 buttonWithType:UIButtonTypeDetailDisclosure
我会得到这个错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[UIButton setInfo:]: unrecognized selector sent to instance 0x753c8c0'
为什么会这样?
最佳答案
只要 UIButton
不提供 initWithType:
方法 - 您就不能子类化“键入的”按钮。您无法创建 extension对于图书馆类(class)。
将某些东西“附加”到预定义对象的唯一方法是使用 associated objects :
#import <objc/runtime.h>
UIButton* btn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
NSString* info = @"foobar";
objc_setAssociatedObject(btn, "info", info, OBJC_ASSOCIATION_RETAIN);
//Later somewhere
NSString* btnInfo = (NSString*)objc_getAssociatedObject(btn, "info");
“信息”可以是您喜欢的任何字符串,它只是稍后检索该对象的键。
OBJC_ASSOCIATION_RETAIN 表示对象将被保留并在 btn
对象的 dealloc:
被调用后自动释放。您可以找到有关该 here 的更多详细信息.
解决您的问题的另一种方法是子类化 UIButton,添加您的信息属性并通过使用 setImage:forState:
方法设置自定义图像使其看起来像披露按钮。
通常,将某些数据与标准 UI 控件耦合是糟糕架构的标志。也许您会后退一步,尝试寻找其他方式将该字符串传递到您需要使用它的地方?
关于ios - UIButtonTypeDetailDisclosure : unrecognised selector sent to instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14822315/