meowmeowmeow meowmeowmeow - 2 months ago 8
Swift Question

draw a colored circle in a UITableViewCell

I'm trying to generate a UITableViewCell with a colored circle on the left.
My plan is to use UIButton and manipulate its layer's corner radius.
However, the colored button never appears.

My xib:

enter image description here

I have an IBOutlet to my ColorHolder UIButton and a variable for its color.

class ColoredCircleCell: UITableViewCell {

@IBOutlet weak var colorHolder: UIButton!
@IBOutlet weak var infoRow1: UILabel!
@IBOutlet weak var infoRow2: UILabel!

var circleColor: CGColor = UIColor.clear.cgColor

override func awakeFromNib() {
super.awakeFromNib()

colorHolder.layer.cornerRadius = colorHolder.bounds.size.height / 2
colorHolder.layer.backgroundColor = circleColor
colorHolder.clipsToBounds = true
}


In my cellForRowAt indexPath:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CircleCell", for: indexPath) as! ColoredCircleCell

print(cell.colorHolder.bounds.size.height)

cell.colorHolder.layer.cornerRadius = cell.colorHolder.bounds.size.height / 2
cell.colorHolder.layer.backgroundColor = UIColor.red.cgColor

cell.infoRow1.text = "H1"

return cell
}


The console tells me that the size of the cell is 1000. I'm guessing it still has not resized with respect to the row height.

EDIT: I've narrowed down the problem to
cell.colorHolder.layer.cornerRadius = cell.colorHolder.bounds.size.height / 2
. The value of
cell.colorHolder.bounds.size.height
is always 1000. How do I extract the correct value AFTER it has been rendered to the screen?

The output:

enter image description here

How do I add a configurable circle for my UITableViewCell?

Answer

posting the answer here for completion's sake. I had to add self.layoutIfNeeded() prior to accessing the bounds. This post helped me out.

override func awakeFromNib() {
        super.awakeFromNib()

        self.layoutIfNeeded()   

        colorHolder.layer.cornerRadius = colorHolder.bounds.size.height / 2
        colorHolder.layer.backgroundColor = circleColor
        colorHolder.clipsToBounds = true
}
Comments