使用scrollViewWillEndDragging的自定义UIScrollView分页

亚历克斯

我正在尝试在iOS 5中使用新的scrollViewWillEndDragging:withVelocity:targetContentOffset:UIScrollView委托调用,但我似乎无法正确地响应我。我正在更改targetContentOffset-> x值,但它永远不会最终被使用。我知道代码正在运行,因为它将在该函数中达到断点。我什至尝试将偏移量值设置为硬编码数字,这样我就知道它将在哪里结束但永远无法正常工作。

有人能正确使用它并使它起作用吗?为了使其正常工作,是否还必须执行其他任何委托调用?

这是我的代码,以防有人发现问题:

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    // goodOffsetX returns the contentOffset i want the scrollView to stop at
    CGFloat goodOffsetX = [self _horizontalContentOffsetForTargetHorizontalContentOffset:(*targetContentOffset).x velocity:velocity.x];

    NSLog( @" " );
    NSLog( @"scrollViewWillEndDragging" );
    NSLog( @"   velocity: %f", velocity.x );
    NSLog( @"   currentX: %f", scrollView.contentOffset.x );
    NSLog( @"   uikit targetX: %f", (*targetContentOffset).x );
    NSLog( @"   pagedX: %f", goodOffsetX );

    targetContentOffset->x = goodOffsetX; 
}
m8labs

您可以使用以下代码实现自定义分页:

- (float) pageWidth {
    return ((UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout).itemSize.width +
    ((UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout).minimumInteritemSpacing;
}

- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    CGFloat pageWidth = self.collectionView.frame.size.width + 10 /* Optional Photo app like gap between images. Or use [self pageWidth] in case if you want the next page be also visible */;

    _currentPage = floor((self.collectionView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;

    NSLog(@"Dragging - You are now on page %i", _currentPage);
}

- (void) scrollViewWillEndDragging:(UIScrollView*)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint*)targetContentOffset {

    CGFloat pageWidth = self.collectionView.frame.size.width + 10; // [self pageWidth]

    int newPage = _currentPage;

    if (velocity.x == 0) { // slow dragging not lifting finger
        newPage = floor((targetContentOffset->x - pageWidth / 2) / pageWidth) + 1;
    }
    else {
        newPage = velocity.x > 0 ? _currentPage + 1 : _currentPage - 1;

        if (newPage < 0)
            newPage = 0;
        if (newPage > self.collectionView.contentSize.width / pageWidth)
            newPage = ceil(self.collectionView.contentSize.width / pageWidth) - 1.0;
    }

    NSLog(@"Dragging - You will be on %i page (from page %i)", newPage, _currentPage);

    *targetContentOffset = CGPointMake(newPage * pageWidth, targetContentOffset->y);
}

当然,您必须设置pageingEnabled = NO。_currentPage是iVar类。感谢http://www.mysamplecode.com/2012/12/ios-scrollview-example-with-paging.html指出了正确的方法。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章