Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScrollview - Off-screen buttons do not fire

I have a UIScrollview that is very long and exceeds the width of the screen. See the below screenshot for reference.

example drawing

I am programatically adding buttons to this scrollview in a dynamically-varying for-loop. There is a "containerView" that basically is the same width of the scrollview, and I'm actually adding the buttons directly onto that. The code is pretty straight-forward there, something like the following:

for (int i=0; i<numberOfButtons; i++) {
    UIButton *currentButton = [[UIButton alloc] init];
    [currentButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [currentButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [currentButton setTag:i];
    [currentButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.containerView addSubview:currentButton];
    // here's where I programatically set constraints for positioning
}

The buttons show perfectly fine in the correct spots, and the ones initially on the screen (i.e. the first 2 in the screenshot example above) fire the "buttonPressed:" method perfectly fine. However, the ones that are initially off-screen still show fine, but the event is not fired when tapped.

I see other similar posts to this out there, but nothing seems to work. Any ideas on where to go on this one? I'm a bit stumped. Thanks in advance!

like image 579
svguerin3 Avatar asked Nov 11 '22 15:11

svguerin3


1 Answers

The answer to this turned out to be exactly what rdelmar indicated in his comment. The containerView's frame was being set to the bounds of the screen size, so when I changed the background color to white, it became obvious that the bounds were limited to the initial screen width.

The fix was pretty simple - once the for-loop completed, I knew exactly how long the containerView needed to be, so I just set the frame there to the appropriate width. Issue resolved!

like image 102
svguerin3 Avatar answered Nov 15 '22 04:11

svguerin3