Ali*_*him 7 ios uicollectionview uicollectionviewlayout swift
我正在尝试使用collectionView实现类似旋转木马的效果.我实现UICollectionView并设置它以水平显示单元格.
唯一的问题是如何只允许一个单元格的出现并将该单元格置于屏幕中心.
注意:启用了分页.
我找到了这个代码,尝试过但遗憾的是没有用
代码参考:使用Swift创建一个Paging UICollectionView
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
if let cv = self.collectionView {
let cvBounds = cv.bounds
let halfWidth = cvBounds.size.width * 0.5;
let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth;
if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(cvBounds) {
var candidateAttributes : UICollectionViewLayoutAttributes?
for attributes in attributesForVisibleCells {
// == Skip comparison with non-cell items (headers and footers) == //
if attributes.representedElementCategory != UICollectionElementCategory.Cell {
continue
}
if let candAttrs = candidateAttributes {
let a = attributes.center.x - proposedContentOffsetCenterX
let b = candAttrs.center.x - proposedContentOffsetCenterX
if fabsf(Float(a)) < fabsf(Float(b)) {
candidateAttributes = attributes;
}
}
else { // == First time in the loop == //
candidateAttributes = attributes;
continue;
}
}
return CGPoint(x : candidateAttributes!.center.x - halfWidth, y : proposedContentOffset.y);
}
}
// Fallback
return super.targetContentOffsetForProposedContentOffset(proposedContentOffset)
}
Run Code Online (Sandbox Code Playgroud)
对于中心单元格,上面的代码是正确的,并且还实现了这两个方法:
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let currentIndex:CGFloat = self.GridCollectionView.contentOffset.x / self.GridCollectionView.frame.size.width
pageControl.currentPage = Int(currentIndex)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width, height: collectionView.frame.size.width+40)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9333 次 |
| 最近记录: |