Search code examples
swiftuitableviewcashapelayer

Why is there a tableview gap between the first cell and the second cell of my tableview? (only happens on iPhone 11)


I wanted to create a tableView with a top having rounded corners (like Apple Music app). So my solution was to apply a modification to the first cell as in the code below.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as? CustomCell
    else {
        fatalError("The dequeued cell is not an instance of Pack.")
    }
    
    if indexPath.row == 0{
        cell.roundCorners([.topLeft,.topRight], radius: cR)
    }

    return cell
}

extension UIView {
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(
            roundedRect: bounds,
            byRoundingCorners: corners,
            cornerRadii: CGSize(width: radius, height: radius))
        
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        
        layer.mask = mask
    }
}

I tested the solution on many devices and it worked well, but when I tried on iPhone 11, there was a small 1px gap appearing between the first and second cell. Does anyone knows why? Is there something special with iPhone 11? Could it be due to a bad practice to round corners this way?

enter image description here


Solution

  • there is a newer way to round corners starting from ios11 that doesn't make the glitch:

    layer.cornerRadius = radius
                layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]