0

I have a UITableView which has a UITableViewCell which contains a UIImageView.

The constraints are setup such that the UIImageView has padding 20 points at the top and sides, and a size ratio of 1:1, so the UIImageView will always be square regardless of the device width.

I apply a cornerRadius to the UIImageView so the image is circular.

However.... the autolayout doesn't seem to work on the first load. But after the first load, it works perfectly.

I have tried every known combination of setNeedsLayout or layoutIfNeeded - both inside the UITableViewCell and in the UITableView code. Nothing works the first time it loads.

Please help!

Code looks like this:

class CircularProfileCell: UITableViewCell {

    @IBOutlet weak var circularView: UIView!
    
    func setup() {
        circularView.layer.cornerRadius = circularView.bounds.height / 2
    }
}

class CircularProfileVC: UITableViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.separatorStyle = .none
        self.tableView.register(UINib(nibName: "CircularProfileCell", bundle: nil), forCellReuseIdentifier: "CircularProfileCell")
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CircularProfileCell", for: indexPath) as! CircularProfileCell
        cell.setup()
        return cell
    }
}

Setup looks like this: enter image description here

theDuncs
  • 4,649
  • 4
  • 39
  • 63

2 Answers2

0

Because corner radius is a layer property it does not always play well with auto layout. In addition, I guess you set it up with frame properties of the view (i.e imageView.layer.cornerRadius = imageView.bounds.height/2). Hence you should try and set the corner radius on the layoutSubviews() function of the cell. This will make sure to render the correct size

override func layoutSubviews() {
  super.layoutSubviews()
  imageView.layer.cornerRadius = imageView.bounds.height/2
  ...
}
CloudBalancing
  • 1,461
  • 2
  • 11
  • 22
0

This only happens when the tableView.separatorStyle = .none

So to fix it I simply leave the separator on, but set the separator color to clear

self.tableView.separatorStyle = .singleLine
self.tableView.separatorColor = UIColor.clear

Thanks to @CloudBalacing for the help. More info about this problem here

theDuncs
  • 4,649
  • 4
  • 39
  • 63