我正在尝试使用集合视图来模拟这种行为。我从使用这个方法开始,它让我更接近了。尽管我在水平分页CollectionView上越往右滑动,内容越移越远。此外,单元格之间的间隔也是关闭的。我相信它需要一个定制的布局,但我不确定。
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width - 20, height: collectionView.frame.height - 20)
}
发布于 2016-06-04 22:04:26
这取决于三个因素:( 1)分段插入;( 2)单元间距;( 3)单元大小
任何变化,你都必须为你的情况改变其他人。
( 1)左、右加20
2)将单元格间距设置为10
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 10
}
func collectionView(collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 10
}
3)设置单元格大小
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width / 1.15 ,height: collectionView.frame.height)
}
4)这将使屏幕中的单元格居中。
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let pageWidth:CGFloat = scrollView.frame.width / 1.15 + cellSpacing ;
let currentOffset:CGFloat = scrollView.contentOffset.x;
let targetOffset:CGFloat = targetContentOffset.memory.x
var newTargetOffset:CGFloat = 0;
if targetOffset > currentOffset
{
newTargetOffset = ceil(currentOffset / pageWidth) * pageWidth;
}
else
{
newTargetOffset = floor(currentOffset / pageWidth) * pageWidth;
}
if newTargetOffset < 0
{
newTargetOffset = 0
}
else if newTargetOffset > scrollView.contentSize.width
{
newTargetOffset = scrollView.contentSize.width;
}
targetContentOffset.memory.x = currentOffset
scrollView.setContentOffset(CGPointMake(newTargetOffset, 0), animated: true)
}
发布于 2019-05-07 17:13:56
我改变了一点@Mohamed的解决方案,它对我来说非常有效:
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let cellSpacing: CGFloat = self.collectionView(self.collectionView, layout: self.collectionView.collectionViewLayout, minimumInteritemSpacingForSectionAt: 0)
let pageWidth: CGFloat = self.pageWidth + cellSpacing
let currentOffset = scrollView.contentOffset.x
let targetOffset = targetContentOffset.pointee.x
targetContentOffset.pointee.x = currentOffset
var pageNumber = 0
if targetOffset > currentOffset {
pageNumber = Int(ceil(currentOffset / pageWidth))
}
else {
pageNumber = Int(floor(currentOffset / pageWidth))
}
let indexPath = IndexPath(row: pageNumber, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
}
https://stackoverflow.com/questions/37636652
复制