我正在尝试通过单元格实现分页,而不是通过Swift中的屏幕实现分页。我在这里找到了解决方案:targetContentOffsetForProposedContentOffset:withScrollingVelocity without subclassing UICollectionViewFlowLayout
以下是我对Swift的理解和转换。
我的子类:
class ChannelFlowLayout: UICollectionViewFlowLayout {
func pageWidth () -> CGFloat {
return itemSize.width + minimumLineSpacing
}
func flickVelocity () -> CGFloat {
return 0.3
}
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
var rawPageValue: CGFloat = collectionView!.contentOffset.x / pageWidth()
var currentPage: CGFloat = (velocity.x > 0.0) ? floor(rawPageValue) : ceil(rawPageValue)
var nextPage: CGFloat = (velocity.x > 0.0) ? ceil(rawPageValue) : floor(rawPageValue)
var pannedLessThanAPage : Bool = fabs(1 + currentPage - rawPageValue) > 0.5
var flicked : Bool = fabs(velocity.x) > flickVelocity()
var targetContentOffset: CGPoint
if pannedLessThanAPage && flicked {
targetContentOffset = CGPoint(x: nextPage * pageWidth(), y: proposedContentOffset.y)
} else {
targetContentOffset = CGPoint(x: round(rawPageValue) * pageWidth(), y: proposedContentOffset.y)
}
return proposedContentOffset
}
}
在我的viewController中:
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
registerNibs()
var layout = ChannelFlowLayout()
collectionView.pagingEnabled = false
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView.collectionViewLayout = layout
}
我错过了什么?非常感谢!