ios - UIButtonTypeDetailDisclosure : unrecognised selector sent to instance

标签 ios cocoa-touch uibutton unrecognized-selector

我有一个自定义按钮类:

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/

相关文章:

ios - branch.io 通用链接不适用于试飞构建

iphone - 如何解决 iPhone 单元测试中 CALayer 类的警告 "No ' -modelLayer' 找到方法

ios - 从 NSArray、KVC 获取最大日期

ios - 我如何获得 UIButton 指针?

ios - Swift:让按钮工作

ios - 如何禁用自定义的 UIButton

iphone - 在方向更改时为 UICollectionView 设置动画

ios - 你可以用一种颜色为 15x15 网格中的一系列 TextView 着色,而另一个用不同的颜色着色吗?

objective-c - Objective-C中通过GET方法发送JSON

iphone - 如何计算特定字体和字体大小的文本字符串的宽度?