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 do register it with 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 height dynamically:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100.0
}
This is a 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)
So I would expect the cell to have height of 100.0 when initialised. But it has a height of 44.0 and only setSelected function returns correct height. At what stage of cell initialisation I should define my custom init, so I could use the cell with height defined by heightForRowAtIndexPath ?
Place the function in layoutSubviews(). You don't put the function there because it is "laying out subviews", but rather because it is the function called in the lifecycle of the cell where you can guarantee that all the subviews of the cell are in fact layed out by the first line of it super.layoutSubviews() and thus contentView.frame will be defined and accurate. There is no guarantee that contentView.frame is accurate in init. A possible place to change frames would be prepareForReuse() as it is a place where you can cleanup and customize your cell before it is reused again. It would look like this:
override func layoutSubviews() {
super.layoutSubviews()
myFunction()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With