gpt4 book ai didi

swift - 如何将自定义 UICollectionViewLayoutAttributes 向下转换为 apply() 方法?

转载 作者:搜寻专家 更新时间:2023-11-01 06:28:02 28 4
gpt4 key购买 nike

我只是找不到如何在自定义单元格的 apply() 方法中访问自定义布局属性。

我必须为我的 CollectionViewLayoutAtrributes 实现自定义布局属性,因此我将它们子类化。到目前为止效果很好:

class TunedLayoutAttributes: UICollectionViewLayoutAttributes {

var customLayoutAttributeValue: CGFloat = 1000

override func copy(with zone: NSZone?) -> Any {
let copy = super.copy(with: zone) as! TunedLayoutAttributes
customLayoutAttributeValue = customLayoutAttributeValue
return copy
}

override func isEqual(_ object: Any?) -> Bool {
if let attributes = object as? TunedLayoutAttributes {
if attributes. customLayoutAttributeValue == customLayoutAttributeValue {
return super.isEqual (object)
}
}
return false
}
}

该值必须根据用户滚动交互动态更改。现在我需要我的自定义单元格在从自定义 UICollectionViewLayout 类调用 invalidateLayout 后更新它们的外观。据我所知,这通常也可以通过覆盖单元格类 apply(_ layoutAttributes: UICollectionViewLayoutAttributes) 方法来完成。

通常是这样的:

override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {

let newFrame = // calculations here. CGRect(....)
layoutAttributes.frame = newFrame
}




现在缺少化学:

与上面的 apply() 示例不同,我的新 customLayoutAttributeValue(当然?)不是方法中 layoutAttributes: 的一部分.

所以我尝试将 layoutAttributes 向下转换为我的自定义类:

override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {

let tunedLayoutAttributes = layoutAttributes as! TunedLayoutAttributes
tunedLayoutAttributes.customLayoutAttributeValue = // calculation here.
}

那么如何在 apply() 方法中访问 tunedLayoutAttributes?任何帮助表示赞赏。感谢阅读!

最佳答案

您在这里为自己提供了解决方案。 UICollectionViewLayoutAttributes(当然)不知道 customLayoutAttributeValue,因此您必须转换为适当的类(TunedLayoutAttributes,在您的情况下)。

现在,为了让 apply(_:) 真正为您提供 TunedLayoutAttributes 而不仅仅是简单的 UICollectionViewLayoutAttributes,您需要告诉您的 UICollectionViewLayout 子类以在为布局中的项目提供布局属性时使用您的自定义类 (TunedLayoutAttributes)。

您可以通过覆盖布局子类中的 class var layoutAttributesClass 来做到这一点。

请注意,如果您在布局子类中覆盖布局属性销售方法(layoutAttributesForElements(in:) 和 friend ),您需要返回 TunedLayoutAttributes整个工作。

另请注意,UIKit 在执行 Collection View 布局传递时经常在后台复制属性,因此请确保您的 copyisEqual 方法是按预期工作。 (例如,传递给 apply(_:) 的属性对象不是(必然)您的布局出售的对象,而是副本。

编辑

正如评论中所讨论的,您应该将强制转换 as! 替换为 if let as? 转换以防止 apply(_:)< 时发生崩溃 实际上通过 UICollectionViewLayoutAttributes 传递。

关于swift - 如何将自定义 UICollectionViewLayoutAttributes 向下转换为 apply() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51360752/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com