I am trying to create rounded corners for a custom cell in my UITableView, I have tried the following.
let cell = tableView.dequeueReusableCell(withIdentifier: "FriendCell", for: indexPath)
let friend = friends[indexPath.row]
cell.textLabel?.text = friend.value(forKey: "name") as? String
cell.textLabel?.textAlignment = .center
cell.layer.cornerRadius = 12
cell.layer.borderColor = UIColor.red.cgColor
The result shows up like this, it is creating the border around the content view as opposed to the view for the cell. If anyone is able to help, it would be much appreciated. Thank you!
2
Answers
If you want to modify the corner radius of cell you should work with contentView layer.
image of cell here
You set the
borderColor
andcornerRadius
but you don’t set theborderWidth
. With a zero border width (The default) you won’t get a border on your layer.If you don’t set the fill color either, the layer also won’t get filled with a different color, and your change to the corner radius won’t have any visible effect.
I agree with @LucaPetra that you should really set the layer properties on the content view rather than the cell, but that shouldn’t prevent your code from working.
Also note that you need to make sure that you fully configure the layer properties on all of your cells, or you will get hard-to-debug cell reuse problems. (If only some of your cells get a border color/width, and you don’t set the border width to 0 on the cells that should not have a border width, sometimes you’ll get a recycled cell that still has a custom border width/color, and that border will show up on the recycled cell next time it’s used as a different cell type.