我正在尝试对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!' 强制类型转换将失败...