我创建了 UIButton 的子类:
//
// DetailButton.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface MyDetailButton : UIButton {
NSObject *annotation;
}
@property (nonatomic, retain) NSObject *annotation;
@end
//
// DetailButton.m
//
#import "MyDetailButton.h"
@implementation MyDetailButton
@synthesize annotation;
@end
我认为我可以通过执行以下操作来创建该对象并设置注释对象:
MyDetailButton* rightButton = [MyDetailButton buttonWithType:UIButtonTypeDetailDisclosure];
rightButton.annotation = localAnnotation;
localAnnotation 是一个 NSObject,但它实际上是一个 MKAnnotation。我不明白为什么这不起作用,但在运行时我收到此错误:
2010-05-27 10:37:29.214 DonorMapProto1[5241:207] *** -[UIButton annotation]: unrecognized selector sent to instance 0x445a190
2010-05-27 10:37:29.215 DonorMapProto1[5241:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UIButton annotation]: unrecognized selector sent to instance 0x445a190'
'
我不明白为什么它甚至要查看 UIButton,因为我已经对其进行了子类化,因此它应该查看 MyDetailButton 类来设置该注释属性。我是否错过了一些非常明显的事情。感觉就是这样:)
预先感谢您提供的任何帮助
罗斯
最佳答案
UIButton 是一个类簇,这意味着 Apple 的 buttonWithType:
实现可能如下所示:
+(id)buttonWithType:(UIButtonType)t {
switch (t) {
case UIButtonTypeDetailDisclosure:
return [[[PrivateDetailDisclosureButtonClass alloc] init] autorelease];
case ...
}
}
因此,当您调用 [MyDetailButton buttonWithType:UIButtonTypeDetailDisclosure];
时,您不会获得 MyDetailButton
的实例,而是获得 PrivateDetailDisclosureButtonClass
的实例>(或者苹果公司实际的称呼)。
但是请注意,如果使用 UIButtonTypeCustom
调用子类,您可以获得 buttonWithType
来实例化子类(至少在运行的模拟器中) v3.0):
// LGButton is a straightforward subclass of UIButton
LGButton *testBtn = [LGButton buttonWithType:UIButtonTypeCustom];
LGButton *testBtn2 = [LGButton buttonWithType:UIButtonTypeDetailDisclosure];
NSLog(@"testBtn: %@, testBtn2: %@", [testBtn class], [testBtn2 class]);
// Output: testBtn: LGButton, testBtn2: UIButton
关于objective-c - 子类化 UIButton 但无法访问我的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2920045/