我正在尝试子类化 UICollectionReusableView
以简化一些代码。我遇到了一个问题,即构建后要“将 View 添加到”什么。
这是我想做的一个例子,以 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
的并行 subview 。所以我写了这个并到达最后一行,但我不确定在我有占位符“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”相似的东西。
最佳答案
简单地做 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
}
关于ios - 子类化 UICollectionReusableView : reference to "content area",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31346316/