Circular UIImageView in UITableView Cell

And it won’t look square in the first time UITableView is displayed.

I assume that you’re already know how to set UITableView and fill it with data.

Many solution on how to display circular image in table view cell is like this :

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier(“TheCell”, forIndexPath: indexPath) as UITableViewCell
  cell.imageView?.image = UIImage(named: “an-image”)
  cell.imageView?.layer.cornerRadius = (cell.imageView?.frame.size.width)! / 2 
  cell.imageView?.layer.masksToBounds = true
  return cell
}

The problem is, when the view controller is displayed the first time, the image view is still in the square shape. Only the “hidden” cell have the circular image view.

The solution is fairly simple. Create a variable to hold the UIImage, and get the width of the image to set the image view corner radius.

let image = UIImage(named: “an-image”)
cell.imageView?.image = image
cell.imageView?.layer.cornerRadius = (image?.size.width)!/2

The reason behind this is that when you set cell.imageView image there’s a very small delay until the image is loaded into imageView and the imageView frame is updated. Because of this, if you access its frame size immediately, the size will always be zero. The “hidden” cell in the first solution will have circular imageView because it reuse the “visible” cell that already have its frame updated when it come into view.

You can try to print / debug it :

cell.imageView?.image = image
print(cell.imageView?.frame.size.width) // > Optional(0.0)
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.