tangobango tangobango - 4 months ago 11
iOS Question

Subclassing UICollectionReusableView: reference to "content area"

I'm trying to subclass

UICollectionReusableView
to simplify some code. I'm running into a problem of what to "add the view to" once it is built.

Here is an example of what I want to do, using UICollectionViewCell as an example:

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) {
...

}
}


Here, when I'm ready to add the
UILabel
, I add it to the contentView. I can't seem to find a parallel subview to
UICollectionReusableView
to refer to. So I write this and get to the last line and I'm not sure what to put where I have the placeholder "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)
}


I'm probably missing some concept here, but I've searched the docs and have found no parallel to "contentView" for the
UICollectionReusableView
.

Answer

simply do 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
}