UIButton inside UIImageView does not respond to taps

后端 未结 3 760
走了就别回头了
走了就别回头了 2020-12-29 20:18

I have a scroll view, which has an image view with an image as a subview, and the image view has a UIButton as one of its subviews. The problem is, I am not abl

相关标签:
3条回答
  • 2020-12-29 20:33

    UIImageView has userInteractionEnabled set to NO/ false by default.

    You are adding the button as a subview to the image view. You should set it to YES / true.

    0 讨论(0)
  • 2020-12-29 20:34

    You can have addInvisibleButtons implementation as

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundColor:[UIColor clearColor]];
    [button addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventAllEvents];
    [button setTitle:@"point" forState:UIControlStateNormal];
    button.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
    self.imageView.userInteractionEnabled = YES;
    [self.imageView addSubview:button];
    

    If you want to have UIButton as completely invisible then you need to remove a line [button setTitle:@"point" forState:UIControlStateNormal]; since it use to show text on UIButton which make it visible.

    This may resolve your issue.

    0 讨论(0)
  • 2020-12-29 20:38

    May I ask why are you adding invisible UIButtons to UIImageView?

    Seems like a bad practice, notice Interface Builder doesn't allow you to add UIButton inside them.

    If you want an image with touch handling, you can:

    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventAllEvents];
    [button setTitle:@"point" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"img.jpg"] forState:UIControlStateNormal];
    [button setFrame:CGRectMake(0.0, 0.0, 40.0, 40.0)];
    
    [scrollView addSubview:button];
    
    0 讨论(0)
提交回复
热议问题