UIScrollView自定义分页大小

时间:2011-07-25 08:11:38

标签: iphone objective-c ipad uiscrollview

在UIScrollView中分页是一个很棒的功能,我需要的是将分页设置为较小的距离,例如我希望我的UIScrollView页面的大小小于UIScrollView的帧宽。 感谢

11 个答案:

答案 0 :(得分:64)

您可以使用UIScrollView委托方法。将您的类设置为滚动视图的委托,然后实现以下内容:

- (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 = round(targetX / (kCellWidth + kCellSpacing));
    if (targetIndex < 0)
        targetIndex = 0;
    if (targetIndex > kMaxIndex)
        targetIndex = kMaxIndex;
    targetContentOffset->x = targetIndex * (kCellWidth + kCellSpacing);
}

速度参数对于确保滚动感觉自然是必要的,并且当手指仍在移动时触摸结束时不会突然结束。单元格宽度和单元格间距是页面宽度和视图中页面之间的间距。在这种情况下,我使用的是UICollectionView

答案 1 :(得分:22)

  1. 将您的scrollView大小更改为您想要的页面大小
  2. 设置scroll.clipsToBounds = NO
  3. 创建一个UIView子类(例如HackClipView)并覆盖hitTest:withEvent:方法

    -(UIView *) hitTest:(CGPoint) point withEvent:(UIEvent *)event
    {     
        UIView* child = [super hitTest:point withEvent:event]; 
        if (child == self && self.subviews.count > 0)  
        {
            return self.subviews[0];
        }
        return child;
    }
    
  4. 设置HackClipView.clipsToBounds = YES

  5. 将您的scrollView放入此HackClipView(具有您想要的总滚动大小)
  6. 有关详细信息,请参阅this answer

    更新的 正如lucius回答中所述,您现在可以实现UIScollViewDelegate协议并使用- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset方法。因为targetContentOffset是一个指针。使用此方法不能保证滚动视图页面的结果相同,因为用户可以一次滚动浏览多个页面。但是将descelerationRate设置为fast几乎给您相同的结果

答案 2 :(得分:11)

您应该禁用分页并在滚动视图中添加UIPanGestureRecognizer并自行处理分页。

- (void)viewDidLoad {

    [super viewDidLoad];
    CGRect viewRect = self.view.bounds; // View controller's view bounds
    theScrollView = [[UIScrollView alloc] initWithFrame:viewRect]; 

    theScrollView.scrollsToTop      = NO;
    theScrollView.pagingEnabled         = NO;
    theScrollView.delaysContentTouches  = NO;
    theScrollView.delegate = self;

    [self.view addSubview:theScrollView];

    UIPanGestureRecognizer * peter = [[[UIPanGestureRecognizer alloc] initWithTarget:self  
                                                                              action:@selector(handlePan:)]
                                       autorelease]; 
    [theScrollView addGestureRecognizer:peter]; 

}

-(void)handlePan:(UIPanGestureRecognizer*)recognizer{

switch (recognizer.state) {
    case UIGestureRecognizerStateBegan:{
        // panStart and startPoint are instance vars for the viewContainer 
        panStart = theScrollView.contentOffset;
        startPoint = [recognizer locationInView:theScrollView]; 


        break;
    }
    case UIGestureRecognizerStateChanged:{

        CGPoint newPoint = [recognizer locationInView:theScrollView];
        CGFloat delta = startPoint.x - newPoint.x;
        if ( abs(delta) > 2)
            theScrollView.contentOffset = CGPointMake( theScrollView.contentOffset.x + delta, 0); 

        CGFloat moveDelta = panStart.x - theScrollView.contentOffset.x;                               


        // current witdh should hold the currently displayed page/view in theScrollView
        if ( abs(moveDelta) > (currentWidth * 0.40)){
            panStart = theScrollView.contentOffset;
            startPoint = newPoint;

            //NSLog(@"delta is bigger"); 
            if ( moveDelta < 0 )
                [self incrementPageNumber]; // you should implement this method and present the next view
            else 
                [self decrementPageNumber]; // you should implement this method and present the previous view

            recognizer.enabled = NO; // disable further event until view change finish

        }

        break; 
    }

    case UIGestureRecognizerStateEnded:
    case UIGestureRecognizerStateCancelled:

        recognizer.enabled = YES; 
        [self showDocumentPage:currentPage]; 

        break;


    default:
        break;
}

}

答案 3 :(得分:3)

可简化重复使用的Swift 4.1解决方案:

Presto 0.194

只需在您的UIScrollView / UITableView / UICollectionView委托中遵守Presto 0.206协议,就可以完成操作,例如:

/// Protocol that simplifies custom page size configuration for UIScrollView.
/// Sadly, can not be done better due to protocol extensions limitations - https://stackoverflow.com/questions/39487168/non-objc-method-does-not-satisfy-optional-requirement-of-objc-protocol
/// - note: Set `.decelerationRate` to `UIScrollViewDecelerationRateFast` for a fancy scrolling animation.
protocol ScrollViewCustomHorizontalPageSize: UIScrollViewDelegate {
    /// Custom page size
    var pageSize: CGFloat { get }

    /// Helper method to get current page fraction
    func getCurrentPage(scrollView: UIScrollView) -> CGFloat

    /// Helper method to get targetContentOffset. Usage:
    ///
    ///     func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    ///         targetContentOffset.pointee.x = getTargetContentOffset(scrollView: scrollView, velocity: velocity)
    ///     }
    func getTargetContentOffset(scrollView: UIScrollView, velocity: CGPoint) -> CGFloat

    /// Must be implemented. See `getTargetContentOffset` for more info.
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
}

extension ScrollViewCustomHorizontalPageSize {
    func getCurrentPage(scrollView: UIScrollView) -> CGFloat {
        return (scrollView.contentOffset.x + scrollView.contentInset.left) / pageSize
    }

    func getTargetContentOffset(scrollView: UIScrollView, velocity: CGPoint) -> CGFloat {
        let targetX: CGFloat = scrollView.contentOffset.x + velocity.x * 60.0

        var targetIndex = (targetX + scrollView.contentInset.left) / pageSize
        let maxOffsetX = scrollView.contentSize.width - scrollView.bounds.width + scrollView.contentInset.right
        let maxIndex = (maxOffsetX + scrollView.contentInset.left) / pageSize
        if velocity.x > 0 {
            targetIndex = ceil(targetIndex)
        } else if velocity.x < 0 {
            targetIndex = floor(targetIndex)
        } else {
            let (maxFloorIndex, lastInterval) = modf(maxIndex)
            if targetIndex > maxFloorIndex {
                if targetIndex >= lastInterval / 2 + maxFloorIndex {
                    targetIndex = maxIndex
                } else {
                    targetIndex = maxFloorIndex
                }
            } else {
                targetIndex = round(targetIndex)
            }
        }

        if targetIndex < 0 {
            targetIndex = 0
        }

        var offsetX = targetIndex * pageSize - scrollView.contentInset.left
        offsetX = min(offsetX, maxOffsetX)

        return offsetX
    }
}

为方便滚动,我还建议设置ScrollViewCustomPageSize

答案 4 :(得分:1)

设置contentOffset -(void)scrollViewDidScroll:(UIScrollView *)scrollView方法。

另请参阅UIScrollViewDelegate refernces

答案 5 :(得分:1)

我遇到了同样的问题所以我制作了一个自定义的UIScrollView。 它现在在Github上可用,因为当我搜索时,我没有找到这样的任何解决方案。请享用! https://github.com/MartinMetselaar/MMCPSScrollView

MMCPSScrollView* scrollView = [[MMCPSScrollView alloc] initWithFrame:self.view.bounds];
[scrollView setType:MMCPSScrollVertical];
[scrollView setPageHeight:250];
[scrollView setPageSize:2];
[self.view addSubview:scrollView];

如果您对此组件有任何其他疑问,请询问。

答案 6 :(得分:0)

我之前遇到过同样的问题。我的方法是在滚动视图中添加第二个UIScrollView。所以你可以切换到页面。在该页面上看起来似乎比页面大于屏幕。我希望它也适用于你的情况。 ; - )

Sandro Meier

答案 7 :(得分:0)

这似乎对我来说好多了:

UIScrollView Custom Paging

这里他们将scrollview(保持其分页的好处)添加为UTIew的ExtendedTouchView或子类的子视图并覆盖命中测试方法

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if ([self pointInside:point withEvent:event]) {
    if ([[self subviews] count] > 0) {
        //force return of first child, if exists
        return [[self subviews] objectAtIndex:0];
    } else {
        return self;
    }
}
return nil;
}

这完全符合我想要的最少的代码和头痛。

答案 8 :(得分:0)

添加手势识别器或其他子视图等是愚蠢的。只需将滚动视图的委托设置为以下内容:

// This is for a vertical scrolling scroll view. 
// Let's say you want it to snap to every 160 pixels :    

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{     
     int y = scrollView.contentOffset.y;
     int yOff = y % 160;
     if(yOff < 80)
          y -= yOff;
     else
          y += 160 - yOff;

     [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, y) animated:YES];
}

// This is for a horizontal scrolling scroll view.
// Let's say you want the same, to snap to every 160 pixels :

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
     int x = scrollView.contentOffset.x;
     int xOff = x % 160;
     if(xOff < 80)
          x -= xOff;
     else
          x += 160 - xOff;

     [scrollView setContentOffset:CGPointMake(x, scrollView.contentOffset.y) animated:YES];
}

答案 9 :(得分:0)

Swift 4.1,iOS11 +:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    targetContentOffset.pointee = CGPoint(
        x: round(targetContentOffset.pointee.x / pageWidth) * pageWidth,
        y: targetContentOffset.pointee.y
    )
}

答案 10 :(得分:-3)

最简单的方法是添加此代码

scrollView.clipsToBounds = false
scrollView.removeGestureRecognizer(scrollView.panGestureRecognizer)
view.addGestureRecognizer(scrollView.panGestureRecognizer)