【发布时间】:2015-07-22 22:30:16
【问题描述】:
我正在尝试继承 UICollectionViewLayoutAttributes 以便我可以添加一个额外的属性 points(CGPoints 的数组)。
子类设计为仅用作装饰视图的属性,因此我需要将成员representedElementCategory 设置为.Decoration。但是representedElementCategory 是只读的,设置它的唯一方法是通过便利的初始化程序:
convenience init(forDecorationViewOfKind decorationViewKind: String, withIndexPath indexPath: NSIndexPath)
查看 Objective-C 头文件,我看到这个便利初始化器实际上被定义为工厂方法:
+ (instancetype)layoutAttributesForDecorationViewOfKind:(NSString *)decorationViewKind withIndexPath:(NSIndexPath*)indexPath;
我希望我的子类的初始化器看起来像:
CustomLayoutAttributes(points: [CGPoint], representedElementKind: String, withIndexPath: NSIndexPath)
但是由于子类不能调用它们父母的便利初始化器,我看不出这是怎么可能的。
我认为子类化的唯一方法是正确的:
class CustomLayoutAttributes: UICollectionViewLayoutAttributes {
var points = [CGPoint]()
}
let attribs = UICollectionViewLayoutAttributes(
forDecorationViewOfKind: "x",
withIndexPath: NSIndexPath(forItem: 0, inSection: 0)
) as! CustomLayoutAttributes
attribs.points = [CGPoint(x: 1.0, y: 2.0), CGPoint(x: 4.0, y: 5.0)]
实际上这行不通,因为 'as!'演员会失败....
【问题讨论】:
-
我应该补充一点,我在自定义 UICollectionViewLayout 中使用这些布局属性,它需要能够创建它们,因此是问题。
标签: ios objective-c swift uicollectionview uicollectionviewlayout