【发布时间】:2016-08-11 11:15:00
【问题描述】:
我正在尝试使用 collectionView 实现类似轮播的效果。我实现了UICollectionView 并将其设置为水平显示单元格。
唯一的问题是我怎样才能只允许一个单元格的出现并将该单元格在屏幕上居中。
注意:分页已启用。
我找到了这段代码,试过了,可惜没用
代码参考:Create a Paging UICollectionView with Swift
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)
}
【问题讨论】:
标签: ios swift uicollectionview uicollectionviewlayout