How do i make it so that when the user scrolls to a new page in UIScrollView, the UIPageControl updates?
I have used this before and it seemed to work well. Be sure to set the UIScrollView.delegate to self.
#pragma mark - UIScrollViewDelegate methods
- (void)scrollViewDidEndDecelerating:(UIScrollView *)sender {
uint page = sender.contentOffset.x / width;
[self.pageControl setCurrentPage:page];
}
Where you defined your UIScrollView and UIPageControl, you have to implement this method :
- (void)scrollViewDidScroll:(UIScrollView *)_scrollView
{
if (pageControlIsChangingPage)
return;
CGFloat pageWidth = _scrollView.frame.size.width;
int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
}
and this one :
- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView
{
pageControlIsChangingPage = NO;
}
where pageControlIsChangingPage
is :
BOOL pageControlIsChangingPage;
Here is an update of this answer for Swift as well:
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
pageControl.currentPage = Int(myScrollView.contentOffset.x) / Int(myScrollView.frame.width)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With