3

我正在尝试子类化 UIButton 以将属性附加到它,但您可能已经猜到我收到“无法识别的选择器发送到实例”错误。

确切错误:[UIButton setAnnotPin:]: unrecognized selector sent to instance

以下是代码的重要部分:

MapViewController.h:

  #import "UIRightPinAccessoryButton.h"

MapViewController.m:

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{ 
 //some other code..

UIRightPinAccessoryButton *rightAccessoryButton = [UIRightPinAccessoryButton buttonWithType:UIButtonTypeDetailDisclosure];
rightAccessoryButton.frame = CGRectMake(0, 0, 35, 35);
rightAccessoryButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
rightAccessoryButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[rightAccessoryButton addTarget:self action:@selector(rightAccessoryButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; 

rightAccessoryButton.annotPin = annot;  **// Error comes here**
}

这是我的 UIRightPinAccessoryButton 类:

UIRightPinAccessoryButton.h

#import "Annotations.h"

@interface UIRightPinAccessoryButton : UIButton{
  Annotations *annotPin;
} 

@property (nonatomic) Annotations *annotPin;

UIRightPinAccessoryButton.m

#import "UIRightPinAccessoryButton.h"

@implementation UIRightPinAccessoryButton

@synthesize annotPin;

@end

我真的不明白为什么 xcode 在 UIButton 上寻找 setAnnotPin: 方法而不是我的自定义 UIRightPinAccessoryButton?

4

1 回答 1

3

本节[UIRightPinAccessoryButton buttonWithType:UIButtonTypeDetailDisclosure];

不会返回类型的对象,UIRightPinAccessoryButton但会返回 UIButton 类型的对象所以将其更改为

UIRightPinAccessoryButton *rightAccessoryButton = [[UIRightPinAccessoryButton alloc] init];

此外,似乎没有办法将按钮的类型更改为 UIButtonTypeDetailDisclosure 一旦其子类化,您可以设置自己的图像以使其看起来相同
而且您不能轻松子类化 buttonWithType,请从iPhone 阅读更多内容:Override UIButton buttonWithType to返回子类

于 2012-06-09T15:40:59.747 回答