Jonnny Jonnny - 1 year ago 47
iOS Question

UITableViewCell doesn't format properly initially

I have a custom

and it used to work fine, but i've upgraded to xcode 8 and I'm still using Swift 2.3 and only just started to notice this problem, so I'm not 100% sure when it started to occur.

I am configuring a cell and all it does is make a label circular and place a number inside it, with a name next to it. It should look like this:

enter image description here

However when the screen initially loads, the circular label is missing. If I scroll down the tableView though and the row leaves the screen, when I scroll back and it becomes in focus again the label appears. The same with the accessory, if I click to edit the row and then return the circle label is generated. Why doesn't it work on the initial load?

Here is the custom code of the UITableViewCell:

func circleLabels(label: UILabel, hex: String){
label.layer.cornerRadius = label.frame.size.width / 2
label.layer.masksToBounds = true

func configureForPlayer(player: Player) {
playerName.text =
jerseyLabel.text = String(player.jersey)
circleLabels(jerseyLabel, hex: "#6470FF")


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PlayerCell", forIndexPath: indexPath) as! PlayerCell
let player = fetchedResultsController.objectAtIndexPath(indexPath) as! Player
return cell

Answer Source

My guess is that label.frame has not yet been set when circleLabels is called for the first time. Once it has been drawn and label.frame has an actual size then the code starts working as expected. If I'm right putting a constant instead of label.frame.size.width / 2 should fix the issue.