【问题标题】:how to Scroll(horizontally) in collection view on button press?如何在按钮按下时在集合视图中滚动(水平)?
【发布时间】:2015-12-01 15:31:26
【问题描述】:

我有一个包含图像的集合视图。我想在按钮按下时执行滚动。我在谷歌上搜索过我发现只设置 contentoffset 但我想滚动动画(如果内容超出滚动区域,滚动应该反弹)。我添加了一个 image 来告诉你我到底要做什么,在图片有一个集合视图,两边的小箭头是按钮。

 @IBAction func moveScrollLeft(sender: UIButton) {
    UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
        self.imageCollectionView.contentOffset.x -= 50
        }, completion: nil)
    print(imageCollectionView.contentOffset.x)
}

@IBAction func moveScrollRight(sender: UIButton) {
    UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
        self.imageCollectionView.contentOffset.x += 50
        }, completion: nil)
    print(imageCollectionView.contentOffset.x)

}

【问题讨论】:

  • UICollectionView 是 UIScrollView 的子类。您可以使用 collectionView.setContentOffset(offset, animated:true)。关于反弹,您必须检查 contentOffset.x + bounds.width > contentSize.width 并为反弹设置动画。

标签: ios swift uicollectionview


【解决方案1】:

使用 UICollectionview 的 scrollToItemAtIndexPath(_:atScrollPosition:animated:) https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionView_class/#//apple_ref/occ/instm/UICollectionView/scrollToItemAtIndexPath:atScrollPosition:animated:

例如:

let indexPath = NSIndexPath(forRow: 3, inSection: 0)
imageCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: true)

【讨论】:

    【解决方案2】:

    请检查此代码,我已修改您的代码:

    @IBAction func moveScrollLeft(sender: UIButton) {
    
            self.imageCollectionView.contentOffset.x -= 50
    
        UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
            }, completion: nil)
                 self.view.layoutIfNeeded()
    
        print(imageCollectionView.contentOffset.x)
    }
    
    @IBAction func moveScrollRight(sender: UIButton) {
    
            self.imageCollectionView.contentOffset.x += 50
    
        UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
        self.view.layoutIfNeeded()
    
            }, completion: nil)
    
        print(imageCollectionView.contentOffset.x)
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2021-12-24
      相关资源
      最近更新 更多