简体   繁体   中英

UIButton as a subview in MKAnnotationView doesn't work

I have added a button to my annotation view, and it appears correctly. When the button is tapped, I want a call to be made, but when I tap the button, it doesn't respond (the button doesn't even highlight). It seems that the button doesn't receive the touch event, but I don't know why.

Here is my code in customAnnotationView.m

- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier
{
    NSLog(@"initWithAnnotation start");

    //initialze the view
    self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
    if (self != nil)
    {
        CGRect frame = self.frame;
        frame.size = CGSizeMake(60.0, 85.0);
        self.frame = frame;
        self.backgroundColor = [UIColor clearColor];
        self.centerOffset = CGPointMake(30.0, 42.0);
    }

    //this has nothing to do with my question
    self.title=[[[NSString alloc] init] autorelease];
    self.description=[[[NSString alloc] init] autorelease];
    self.phoneNumber=[[[NSString alloc] init] autorelease];
    customAnnotation * tempCust = (customAnnotation *)annotation;       
    self.title=annotation.title;
    self.description=tempCust.description;
    self.phoneNumber=tempCust.phoneNumber;

    //here is the question button
    self.userInteractionEnabled=YES;
    self.exclusiveTouch=NO;
    UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"Call" forState:UIControlStateNormal];
    //decide the button's position
    CGRect rect=button.frame;
    rect.origin.x=15;
    rect.origin.y=47;
    rect.size.width=40;
    rect.size.height=20;
    button.frame=rect;
    [self addSubview:button];

    [button becomeFirstResponder];

    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];



    NSLog(@"initWithAnnotation finished");

    return self;
}

//action method
-(void)buttonClicked:(id)sender{
    NSString *callNumber=[[[NSString alloc] initWithFormat:@"tel://%@",self.phoneNumber] autorelease];
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:callNumber]];
}

Why doesn't the button work?

self.rightCalloutAccessoryView = button;

Use the above instead of [self addSubview:button];

Hope this help's you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM