Home > OS >  Adding a Corner Radius to a Custom Cell in a UITableView
Adding a Corner Radius to a Custom Cell in a UITableView

Time:10-24

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!

https://i.stack.imgur.com/mf1kk.png

CodePudding user response:

If you want to modify the corner radius of cell you should work with contentView layer.

cell.contentView.layer.backgroundColor = UIColor.lightGray.cgColor
cell.contentView.layer.borderWidth = 1.5
cell.contentView.layer.cornerRadius = 12
cell.contentView.layer.borderColor = UIColor.red.cgColor

image of cell here

CodePudding user response:

You set the borderColor and cornerRadius but you don’t set the borderWidth. 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.

  • Related