ios - 子类化 UICollectionReusableView : reference to "content area"

标签 ios swift uicollectionview subclass

我正在尝试子类化 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/

相关文章:

ios - 正确更新 NSManagedObject 关系

ios - Flex 移动项目 : Open PDF in Native Reader on iOS

ios - Swift 扩展 - 必须在非专用泛型类型 'Array' 上声明约束扩展

swift - iOS11 键盘问题

ios - UICollectionViewCell 未显示

ios - CustomTableCell 中的 UICollectionView

ios - 如何从 UICollectionView Cell 转到另一个 ViewController Swift

objective-c - UIButton @selector如何工作?

ios - 使用 Swift 构建 Cocoapod 并依赖于 Objective-C 框架

ios - 不显示横幅仅在收到推送通知时振动设备