我正在尝试将UICollectionReusableView
子类化以简化一些代码。我遇到了一个问题,即一旦构建它就会“添加视图”。
以下是我想要做的一个例子,以UICollectionViewCell为例:
class CVCell: UICollectionViewCell {
let textLabel: UILabel!
override init(frame: CGRect) {
let textFrame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
textLabel = UILabel(frame: textFrame)
super.init(frame: frame)
textLabel.font = UIFont.systemFontOfSize(10)
textLabel.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
textLabel.textAlignment = NSTextAlignment.Center
textLabel.backgroundColor = UIColor.clearColor()
contentView.addSubview(textLabel)
}
required init(coder aDecoder: NSCoder) {
...
}
}
在这里,当我准备添加UILabel
时,我将其添加到contentView。我似乎无法找到UICollectionReusableView
引用的并行子视图。所以我写了这个,然后到了最后一行,我不确定在占位符“ConfusionHere”的地方放什么:
class CVHeaderView: UICollectionReusableView {
let textLabel: UILabel!
override init(frame: CGRect) {
let textSize = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
textLabel = UILabel(frame: textSize)
super.init(frame: frame)
textLabel.font = UIFont.systemFontOfSize(10)
textLabel.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
textLabel.textAlignment = NSTextAlignment.Center
textLabel.backgroundColor = UIColor.clearColor()
ConfusionHere.addSubview(textLabel)
}
我可能在这里遗漏了一些概念,但我搜索了文档,发现UICollectionReusableView
的“contentView”没有找到平行。
答案 0 :(得分:3)
只需做self.addSubView(textLabel)
class CVHeaderView: UICollectionReusableView {
let textLabel: UILabel!
override init(frame: CGRect) {
let textSize = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
textLabel = UILabel(frame: textSize)
super.init(frame: frame)
textLabel.font = UIFont.systemFontOfSize(10)
textLabel.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
textLabel.textAlignment = NSTextAlignment.Center
textLabel.backgroundColor = UIColor.clearColor()
self.addSubview(textLabel) // confusion removed
}