Ios 如何在按下按钮时在集合视图中滚动(水平)?
我有一个包含图像的集合视图。我想在按下按钮时执行滚动。我在谷歌上搜索过,我发现只设置了contentoffset,但我想用动画滚动(如果内容超过了滚动区域,滚动应该会反弹)。我添加了一个图标来告诉你我到底要做什么,在图片中有一个集合视图,两侧的小箭头是按钮Ios 如何在按下按钮时在集合视图中滚动(水平)?,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,我有一个包含图像的集合视图。我想在按下按钮时执行滚动。我在谷歌上搜索过,我发现只设置了contentoffset,但我想用动画滚动(如果内容超过了滚动区域,滚动应该会反弹)。我添加了一个图标来告诉你我到底要做什么,在图片中有一个集合视图,两侧的小箭头是按钮 @IBAction func moveScrollLeft(sender: UIButton) { UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimation
@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的
scrollToItemAtIndexPath(uuz:atScrollPosition:animated:)
:
例如:
let indexPath = NSIndexPath(forRow: 3, inSection: 0)
imageCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: true)
使用UICollectionview的
scrollToItemAtIndexPath(uuz:atScrollPosition:animated:)
:
例如:
let indexPath = NSIndexPath(forRow: 3, inSection: 0)
imageCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: true)
请检查此代码我已修改您的代码:
@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)
}
请检查此代码我已修改您的代码:
@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)
}
UICollectionView是UIScrollView的一个子类。您可以使用collectionView.setContentOffset(偏移,动画:true)。关于反弹,您必须检查contentOffset.x+bounds.width>contentSize.width并设置反弹动画。UICollectionView是UIScrollView的子类。您可以使用collectionView.setContentOffset(偏移,动画:true)。关于反弹,您必须检查contentOffset.x+bounds.width>contentSize.width并设置反弹动画。