Kostarev Kirill
Kostarev Kirill

Reputation: 184

The custom cell in the table view does not want to be rounded

everyone!

My problem sound like this:
I want to make my custom cell rounded in my app in iPhone. But when I try to do something like this:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? MainTableViewCell
        else { fatalError("DequeueReusableCell failed while casting") }
    cell.imageView?.layer.cornerRadius = cell.frame.size.height / 2
    cell.imageView?.clipsToBounds = true
    cell.imageView?.contentMode = .scaleAspectFill
    cell.textLabel?.textColor = #colorLiteral(red: 0.03921568627, green: 0.3969546359, blue: 1, alpha: 1)
    cell.textLabel?.font = UIFont(name: "EuphemiaUCAS", size: 22)
    cell.textLabel?.text = restaurantNames[indexPath.row]
    cell.textLabel?.numberOfLines = 0
    cell.imageView?.image = UIImage(named: restaurantNames[indexPath.row])
    return cell
}
// MARK: - Table View Delegate
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 85
}

I have a strange result: Result #1

But when I change this line:

cell.imageView?.layer.cornerRadius = cell.frame.size.height / 2

To this:

cell.imageView?.layer.cornerRadius = 85 / 2

As you can see, everything is in order: Result #2

But this is not the right way to solve the problem

Thanks for all answers!

Upvotes: 2

Views: 71

Answers (3)

Jawad Ali
Jawad Ali

Reputation: 14397

Add it in your cell class instead of cellForRow

class MainTableViewCell: UITableViewCell {

    override func layoutSubviews() {
    imageOfPlace.layer.cornerRadius = imageOfPlace.bounds.midY // or imageOfPlace.bounds.height/2
    imageOfPlace.clipsToBounds = true
   }
}

Upvotes: 1

Muzahid
Muzahid

Reputation: 5186

UITableView provides default sizes for rows when you dequeue cells. That's why cell.frame.size.height/2 is not 85/2 rather than detaultHeight / 2. TableView cell height later becomes fix when heightForRowAt delegate method called. You can find more about this Here.

Change the corner radius property of imageView in awakeFromNib method under MainTableViewCell.

class MainTableViewCell: UITableViewCell {
    override func awakeFromNib() {
        imageView.layer.cornerRadius = bounds.height/2 
    }
}

Upvotes: 0

Quang Dam
Quang Dam

Reputation: 325

The problem has come because the cellForRow AtIndexPath called before heightForRowAt indexPath called. It's a reason why the cell at that time has default height size, and you used it to calculate cornerRadius.

You can use your way to fix the problem, or you use the image to look like a mask to put in above the image in the cell. This way can help you use less energy for calculating cornerRadius when the delegate is called.

Upvotes: 0

Related Questions