UIScrollView custom paging size

后端 未结 11 1495
走了就别回头了
走了就别回头了 2020-12-07 11:49

paging in UIScrollView is a great feature, what I need here is to set the paging to a smaller distance, for example I want my UIScrollView to page less size that the UIScrol

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 12:22

    There is a UIScrollView delegate method you can use. Set your class as the scroll view's delegate, and then implement the following:

    - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
    {
        CGFloat kMaxIndex = 23;
        CGFloat targetX = scrollView.contentOffset.x + velocity.x * 60.0;
        CGFloat targetIndex = 0.0;
        if (velocity.x > 0) {
            targetIndex = ceil(targetX / (kCellWidth + kCellSpacing));
        } else if (velocity.x == 0) {
            targetIndex = round(targetX / (kCellWidth + kCellSpacing));
        } else if (velocity.x < 0) {
            targetIndex = floor(targetX / (kCellWidth + kCellSpacing));
        }
        if (targetIndex < 0)
            targetIndex = 0;
        if (targetIndex > kMaxIndex)
            targetIndex = kMaxIndex;
        targetContentOffset->x = targetIndex * (kCellWidth + kCellSpacing);
        //scrollView.decelerationRate = UIScrollViewDecelerationRateFast;//uncomment this for faster paging
    }
    

    The velocity parameter is necessary to make sure the scrolling feels natural and doesn't end abruptly when a touch ends with your finger still moving. The cell width and cell spacing are the page width and spacing between pages in your view. In this case, I'm using a UICollectionView.

提交回复
热议问题