1

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?

meowmeowmeow
  • 713
  • 7
  • 17

3 Answers3

0

I think your set colorbutton constraint like topspace to superview and bottomspace to superView.

If that's the case than remove bottomspace to superView and add height constraint.

than do this

cell.colorHolder.layer.cornerRadius = cell.colorHolder.bounds.size.height / 2
cell.colorHolder.clipToBounds = true

and it should display as circle.

Hope this will solve your problem

Kuntal Gajjar
  • 792
  • 6
  • 12
0

Just override layoutSubviews and set your corner radius there.

- (void)layoutSubviews {
   [super layoutSubviews];
   self.colorHolder.layer.cornerRadius = self.colorHolder.bounds.size.height / 2;
}
almas
  • 7,090
  • 7
  • 33
  • 49
0

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
}
meowmeowmeow
  • 713
  • 7
  • 17