Reputation: 472
I'm new to XCode so I need your help please. I use a UIPageControl to show which cell of my collection View is now visible.
The problem is to get the visible cell:
I think in this Method
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
I should update the current Page. But how do I get the current Page?
Thanks for your help! :-)
Upvotes: 4
Views: 4008
Reputation: 62676
The page can be defined as the ratio between the offset and the size.
- (NSInteger)horizontalPageNumber:(UIScrollView *)scrollView {
CGPoint contentOffset = scrollView.contentOffset;
CGSize viewSize = scrollView.bounds.size;
NSInteger horizontalPage = MAX(0.0, contentOffset.x / viewSize.width);
// Here's how vertical would work...
//NSInteger verticalPage = MAX(0.0, contentOffset.y / viewSize.height);
return horizontalPage;
}
There are a couple ways to trigger this. You can do the work on every scrollViewDidScroll, but that's a bit excessive. A better way is to run it either when dragging is complete and there will be no further deceleration, or when deceleration ends, as follows:
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
self.page.currentPage = [self horizontalPageNumber:scrollView];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
if (!decelerate) self.page.currentPage = [self horizontalPageNumber:scrollView];
}
Upvotes: 11
Reputation:
If you use the pager, than is is the code should help you:
- (IBAction)pagerValueChanged
{
NSData* imgData = [images objectAtIndex:pager.currentPage];
UIImage* img = [[UIImage alloc]initWithData:imgData];
imageView.image = img;
//NSLog(@"img width: %f, img height: %f", img.size.width, img.size.height);
[img release];
}
Upvotes: 0