【发布时间】:2011-08-19 10:56:54
【问题描述】:
几天来,我一直在尝试寻找一种方法来调用自定义按钮上的 action:selector,该按钮源自 UIButton,我想将其与 pin 注释相关联。我使用子类的原因是我想将一些数据传递给这个按钮对象,以便在按下按钮时显示另一个 UIView 显示这些数据。
问题是在执行时,当我点击 pin 注释时,它会打开它的按钮,当我点击它时,什么也没有发生。我在此处设置的touchupInside 事件不会调用我的showDetails: 方法:
[rightButton addTarget:self
action:@selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
我的问题是如何继承UIButton的方法,如addTarget:action:forControlEvents:,buttonWithType:等,以便在我的子类中使用它们?
这是有关问题的完整代码:
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{
MKPinAnnotationView *annView=[[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:@"MyPin"] autorelease];
annView.animatesDrop=FALSE;
annView.canShowCallout = YES;
[annView setSelected:YES];
if ([[annotation title] isEqualToString:@"Current Location"]) {
annView.pinColor = MKPinAnnotationColorRed;
}
else {
annView.pinColor = MKPinAnnotationColorPurple;
}
annView.calloutOffset = CGPointMake(-5, 5);
PlaceMark *pm=(PlaceMark *)annotation;
AddressItem *ai=[pm getData];
//Another problem is that i cant set buttonWithType:UIButtonTypeDetailDisclosure cause it generate error cause it is a method of UIbutton superclass
MyDetailButton* rightButton = [MyDetailButton buttonWithType:UIButtonTypeCustom];
[rightButton setData:ai];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
[rightButton addTarget:self action:@selector(showDetails:) forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = rightButton;
return annView;
}
提前谢谢你。我希望我已经对我的问题给出了明确的解释。
【问题讨论】:
-
不要继承 UIButton - 请参阅this SO question。
-
感谢您的回复。但这与您建议我的链接中的问题有点不同。因为我需要将数据传递到按钮中,这就是我使用子类的原因。我需要做的是将人员数据从特定的引脚注释传递到新视图以显示它们。像这样:单击包含人员数据的引脚注释时(它们在地图中是多个),这应该显示另一个视图显示这些人员数据。这就是为什么我想向 MKPinAnnotationView 对象添加一个个性化按钮,但我对此有疑问。可以存在另一个解决方案来代替它吗?谢谢
-
如果你是 UIButton 的子类,这样你就可以在每个按钮中嵌入用户信息,你不需要这样做。相反,您应该实现 2 个委托方法: mapView:annotationView:calloutAccessoryControlTapped: 和 mapView:didSelectAnnotationView: 这两个都会告诉您视图。所以参考 view.annotation 以了解哪个底层数据项与该引脚相关联,并且您应该能够从注释中找出那是谁。
-
UIButton 是一个具体的类,而不是类簇。我已经将 UIButton 子类化了,没有任何问题。 Apple 非常明确地告诉您哪些类可以子类化和不能子类化。
标签: iphone objective-c cocoa-touch uibutton subclass