I have a UIScrollView that scrolls automatically, and I create several buttons using initWithFrame, each with an image and an unique action(method) and add them all to the scroll view. The buttons' images can be scrolling automatically with the scroll view but when I click on each button, it's not the method I assigned to that button. When I click on the same position, no matter which buttons pass by, it goes to the same method instead of the method of that button. Below is my code for creating the buttons:
for (int i = 0; i < 4; i++) {
//create an imageView object in every 'page' of the scrollView.
CGRect frame;
frame.origin.x = 62 * i;
frame.origin.y = 0;
frame.size = CGSizeMake(52.0, 52.0);
myButton = [[UIButton alloc] initWithFrame:frame];
[myButton setImage:[MyImageArray objectAtIndex:i] forState:normal];
switch (i) {
case 0:
[myButton addTarget:self action:@selector(aMethod0) forControlEvents:UIControlEventTouchUpInside];
break;
case 1:
[myButton addTarget:self action:@selector(aMethod1) forControlEvents:UIControlEventTouchUpInside];
break;
case 2:
[myButton addTarget:self action:@selector(aMethod2) forControlEvents:UIControlEventTouchUpInside];
break;
case 3:
[myButton addTarget:self action:@selector(aMethod3) forControlEvents:UIControlEventTouchUpInside];
break;
default:
break;
}
[self.MyScrollView addSubview:myButton];
Below is the code for the automatically scroll the scrollview:
- (void)move_pagination {
UIPageControl *pgCtr = MyPageControl;
CGFloat contentOffset = MyScrollView.contentOffset.x;
__block int nextPage = (int)(contentOffset/(MyScrollView.frame.size.width+10)) + 1 ;
[UIView animateWithDuration:10
delay:0
options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
animations:^{
if( nextPage!=3 ) {
MyScrollView.contentOffset = CGPointMake(nextPage*(10+MyScrollView.frame.size.width), 0);
pgCtr.currentPage=nextPage;
// else start sliding from 1 :)
} else {
nextPage = 1;
MyScrollView.contentOffset = CGPointMake(0, 0);
MyScrollView.contentOffset = CGPointMake(nextPage*(10+MyScrollView.frame.size.width), 0);
pgCtr.currentPage=2;
}
}
completion:nil];
}
Any clues why this strange behaviour happens?? Thanks.