简体   繁体   中英

Custom UIButton not working within UIImageView

Background: Part of my app is an exhibition floor plan that is zoomable/scrollable and each of the stands on the floor plan will have a button overlay that, when pressed, will display information about that exhibitor.

What I have done so far: I have created a UIViewController on a storyboard. When this UIVC loads, a UIScrollView is added programatically and a UIImageView is then added to that. I have then added a UIButton onto the UIIV that displays ok (as a green box) but it's action selector is never fired.

Code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [docPaths objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/nia_floorplan.png", docDirectory];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
    _imageView = [[UIImageView alloc] initWithImage:image];

    CGFloat screenWidth = self.view.frame.size.width;
    CGFloat screenHeight = self.view.frame.size.height;
    CGFloat scrollViewWidth = (screenWidth * 0.9);
    CGFloat scrollViewHeight = (screenHeight * 0.83);
    CGFloat scrollViewLeft = (screenWidth * 0.05);
    CGFloat scrollViewTop = (screenHeight * 0.03);

    self.scrollView =[[UIScrollView alloc] initWithFrame:CGRectMake(loginOverlayLeft, loginOverlayTop, loginOverlayWidth, loginOverlayHeight)];

    [self buildHotspots];
    [_scrollView addSubview:_imageView];

    [_scrollView setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.7f]];
    [_scrollView setMaximumZoomScale:3.5];
    [_scrollView setClipsToBounds:YES];
    [_scrollView setMinimumZoomScale:1.0];
    [_scrollView setDelegate:self];
    [_scrollView setBounces:NO];
    [_scrollView setContentSize:[image size]];

    [self.view addSubview:_scrollView];
    [self.view bringSubviewToFront:testBtn];

}

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return _imageView;
}

-(void)buildHotspots {
    testBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    testBtn.frame = CGRectMake(364, 267, 37, 61);
    [testBtn setBackgroundColor:[[UIColor greenColor]colorWithAlphaComponent:0.7f]];
    [testBtn addTarget:self action:@selector(displayInfo) forControlEvents:UIControlEventTouchUpInside];
     [_imageView addSubview:testBtn];
}

-(void)displayInfo{
    NSLog(@"Button pressed");
}

By default UIImageView has userInteractionEnabled set to NO . Just set it to YES and your UIButton will receive touch events.

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