Objective-C : UIScrollView manual paging

﹥>﹥吖頭↗ 提交于 2019-12-04 18:54:19

Change the frame of the scrollview to be as if it were only displaying the middle view (i.e. a third of its original width, and offset by the same amount), but then set its clipsToBounds property to NO.

I found a solution if anyone else is interested.

Assign you view the delegate of a scrollview. Ovveride scrollViewDidEndDecelerating, afterwards get your current index(page you want) by doing something like.

 NSNumber* currentIndex = [NSNumber numberWithInt:round(scrollview.Contentoffset.x / PAGE_SIZE)];

//Then just update your scrollviews offset with


[scrollview setContentOffset:CGPointMake([currentIndex intValue] * PAGE_SIZE, 0) animated:YES];

Since iOS 5, there's the scrollViewWillEndDragging:withVelocity:targetContentOffset: delegate method on UIScrollViewDelegate. This allows you to implement arbitrary paging.

For this to work, you first need to set the pagingEnabled property to NO, otherwise the delegate method I'm talking about isn't called. The scroll view now calls this delegate method whenever the user lifts his finger and the scroll view wants to determine where to finish the scrolling.

The magic is the last argument, targetContentOffset: it's a pointer to a CGPoint and used as a in/out variable. This means this variable tells you where the scrollview wants to scroll to. But it allows you modify this target location. The velocity might also be of interest, it can give you an indication whether the user "pushed" the scroll view or moved it, stopped, then lifted his finger.

For example, here's an implementation that rounds the target x location to the nearest multiple of 100, thus making "pages" of 100 points width.

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    targetContentOffset->x = round(targetContentOffset->x / 100.0) * 100.0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!