Latcie
Latcie

Reputation: 701

Cell image view cornerRadius in swift

Where would I best set the cornerRadius property?

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 1/6 * tableView.bounds.width
}

I have tried it in the cell's awakeFromNib, but it doesn't yet seem to have the proper height.

Upvotes: 0

Views: 895

Answers (2)

Damo
Damo

Reputation: 12900

Okay warning - all untested code

If you assume that the object which knows best how to draw a cell, is the cell itself....

Create a subclass of the Cell

class MyUITableViewCell: UITableViewCell

Now, there are many ways to skin this cell. My preference is to:

Add a method for all of the little things you wish to change in the cell

func configure () {

    self.layer.cornerRadius = 5.0 // for instance

}

When should you call configure?

Arguably you could call in in draw() but I like to

Call configure() via the delegate

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if cell.responds(to: #selector(MyUITableViewCell.configure()) {

        cell.configure()

    }
}

Upvotes: 0

Adrien
Adrien

Reputation: 166

If the image view size if flexible and the corner radius is linked to the image size, I advise you to set the corner radius in the layoutSubviews() method of your cell.

You can set it as following:

override func layoutSubviews() {
    super.layoutSubviews()
    imageView.layer.cornerRadius = imageView.frame.size.width/2.0
}

Upvotes: 4

Related Questions