When to initiate a custom view in a UITableViewCell subclass?

I am trying to subclass a cell, but the frame size I get in init()

is not the one I set in heightForRowAtIndexPath

.

class MyCell: UITableViewCell {

override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    initCell()
}
required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    initCell()
}
override func awakeFromNib() {
    super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    println("ContentViewFrame IN SET SELECTED: \(self.contentView.frame)")
}

func initCell() {
    println("ContentViewFrame IN initCell: \(self.contentView.frame)")
}
}

      

I'll register it with a tabelView:

myTable.registerClass(MyCell.self, forCellReuseIdentifier: "awesomeCell")

      

Use it:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("conversationCell", forIndexPath: indexPath) as ConversationCell
    return cell
}

      

Set the height dynamically:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 100.0
}

      

This is the console output:

ContentViewFrame IN initCell: (0.0,0.0,320.0,44.0)
ContentViewFrame IN SET SELECTED: (0.0,0.0,320.0,99.5)
ContentViewFrame IN SET SELECTED: (0.0,0.0,320.0,99.5)

      

Thus, I would expect the cell to be 100.0 high when initialized. But it has a height of 44.0 and only the function setSelected

returns the correct height. At what stage of cell initialization should I define my custom init so I could use a cell with a height defined heightForRowAtIndexPath

?

+3


source to share


1 answer


Place the function in layoutSubviews()

. You don't put a function there because it is "laying out subplots", but rather because it is a function called in the lifecycle of a cell where you can ensure that all subzones of a cell are actually laid out first by its row super.layoutSubviews()

and therefore contentView.frame

will be defined and accurate ... There is no guarantee what contentView.frame

is exact in init. A possible place to change frames would be prepareForReuse()

, as this is where you can clean and tweak your cell before reusing it. It will look like this:



override func layoutSubviews() {
    super.layoutSubviews()
    myFunction()
}

      

+3


source







All Articles