Pass parameter on selector of UIButton

与世无争的帅哥 提交于 2019-12-02 08:17:37

问题


I have a detailDisclousure button on the callout of a MKAnnotation. When this button is pressed I need to call a method passing a parameter that identifies the annotation that called it. How could it be done?

this is my viewForAnnotation:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{

if ([annotation isKindOfClass:[Annotation class]])
{
    static NSString* identifier = @"identifier";

    MKPinAnnotationView* pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];

    if (pinView == nil) 
    {
        pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier]autorelease];
    }

    Annotation *antt = annotation;

    pinView.canShowCallout = YES;
    pinView.draggable =    YES;

    UIButton* detailButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    [detailButton performSelector:@selector(goToViewWithAnnotation:) withObject:antt];

    pinView.rightCalloutAccessoryView = detailButton;

    return pinView;
}

else 
{
    return nil; 
}
}

And this is the method that should be called with the parameter:

-(void)goToViewWithAnnotation:(Annotation *)annotation
{
    NextViewController *nextView = [[NextViewController alloc]initWithNibName:@"NextViewController" bundle:nil];

nextView.id = annotation.id;

[self.navigationController nextView animated:YES];
}

回答1:


you can pass any NSInteger via the tag property of the UIButton only.




回答2:


It's not possible to send data with the -addTarget:action:forControlEvent: for UIButton:

[detailButton addTarget:self action:@selector(goToViewWithAnnotation:) forControlEvents:UIControlEventTouchUpInside];

Try to handle the data with some other way, when you trigger the selector. Like saving a pointer or var as you like.

UIButton have these callers as you can see:

- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event



回答3:


I think you can add a property(which is (Annotation *)annotation) in .h file. Then you can use annotation in the "-(void)goToViewWithAnnotation" method. Or you can customized a new button which inherits UIControl



来源:https://stackoverflow.com/questions/11613906/pass-parameter-on-selector-of-uibutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!