Azi*_*ode 3 ios uicollectionview swift
我的水平UICollectionView中有40个单元格和一个按钮.
当我点击按钮时,我可以从5号单元格跳转到10号单元格.
但是一旦我想要进一步的细胞(例如从5到25),
它不起作用,而是变为0.
码:
func setValue(value: Int, animated: Bool) {
self.value = value
if let row = find(values, value) {
let indexPath = NSIndexPath(forRow: row, inSection: 0)
selectedCell = collectionView.cellForItemAtIndexPath(indexPath) as? StepperCell
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: animated)
}
}
override func prepareLayout() {
let start = Int(collectionView!.bounds.size.width * 0.5) - statics.width / 2
let length = collectionView!.numberOfItemsInSection(0)
if cache.isEmpty && length > 0 {
for item in 0..<length {
let indexPath = NSIndexPath(forItem: item, inSection: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = CGRect(
x: start + (statics.width + statics.padding) * indexPath.item,
y: 0,
width: statics.width,
height: statics.height
)
cache.append(attributes)
}
contentWidth = CGRectGetMaxX(cache.last!.frame) + CGFloat(start)
}
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache {
if CGRectIntersectsRect(attributes.frame, rect) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
}
Run Code Online (Sandbox Code Playgroud)

我认为你可以省去行逻辑.毕竟 - 你只是使用传递Int.如果您的if let子句失败,则不会滚动.
此外,将呼叫放到cellForItemAtIndexPath- 您不需要它(您也没有使用它).
我想也许你应该使用NSIndexPath(forItem, inSection)而不是NSIndexPath(forRow, inSection).(表视图使用row,collectionView使用item.)
collectionView.scrollToItemAtIndexPath(
NSIndexPath(forItem: value, inSection: 0),
atScrollPosition: .CenteredHorizontally, animated: true)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1536 次 |
| 最近记录: |