【发布时间】:2015-04-28 10:25:45
【问题描述】:
更新
使用指定的collectionViewContentSize() 方法时,问题似乎已解决,如下所示:
let contentSize = collectionViewContentSize()
尽管如此,我对这种行为背后的解释非常感兴趣,因此我已经相应地更新了我的问题。
原始问题
我正在尝试重新创建this article 的第一个示例中的步骤,但使用的是 Swift 和 Storyboard。
我有一个自定义的UICollectionViewFlowLayout 子类,其内容如下:
导入 UIKit
class SpringyFlowLayout: UICollectionViewFlowLayout {
private lazy var animator: UIDynamicAnimator = {
return UIDynamicAnimator(collectionViewLayout: self)
}()
override func prepareLayout() {
super.prepareLayout()
let contentSize = collectionView!.contentSize
let items = super.layoutAttributesForElementsInRect(CGRect(origin: CGPointZero, size: contentSize)) as! [UICollectionViewLayoutAttributes]
if animator.behaviors.isEmpty {
for item in items {
let spring = UIAttachmentBehavior(item: item, attachedToAnchor: item.center)
spring.length = 0
spring.damping = 0.8
spring.frequency = 1.0
animator.addBehavior(spring)
}
}
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
return animator.itemsInRect(rect)
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
return animator.layoutAttributesForCellAtIndexPath(indexPath)
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
let delta = newBounds.origin.y - collectionView!.bounds.origin.y
for spring in animator.behaviors {
let items = spring.items as! [UICollectionViewLayoutAttributes]
if let attributes = items.first {
attributes.center.y += delta
animator.updateItemUsingCurrentState(attributes)
}
}
return false
}
我在 Storyboards 中设置了正确的 Layout 类。当我运行应用程序时,我的 Collection View 是空的。
我已确定问题出在以下片段中:
override func prepareLayout() {
super.prepareLayout()
let contentSize = collectionView!.contentSize
let items = super.layoutAttributesForElementsInRect(CGRect(origin: CGPointZero, size: contentSize)) as! [UICollectionViewLayoutAttributes]
//...
}
由于我继承了UICollectionViewFlowLayout,我想我可以依靠超级实现为我布置元素,然后修改它们的属性。但是当我检查 contentSize 时,它会正确报告宽度,但高度是 0。
这会导致一个空的 items 数组 -> animator 中没有任何行为 -> animator.itemsInRect(_) 返回一个空数组 -> 空的 Collection View。
我似乎无法找出我错过了什么。应该不需要重写contentSize() 方法,因为我使用的是流布局。
【问题讨论】:
标签: ios swift uicollectionview uicollectionviewlayout uikit-dynamics