Mr.Javed Multani
Mr.Javed Multani

Reputation: 13294

I am trying for corner radius to view which is placed inside UITableView. It doesn't work for me

I am trying to give corner radius to UIView which is placed in UITableViewCell. I need to display section like corner radius for every section so I am giving first cell to top right and top left corner radius and for the last cell to bottom right and bottom left corner radius. But it's not works for me.

Here is my code: This is for the first cell (row) of UITableView

cell.viewMain.roundCorners(corners: [.topLeft, .topRight], radius: 10.0)
cell.layoutSubviews()
cell.layoutIfNeeded()

This is for the last cell (row) of UITableView

cell.viewMain.roundCorners(corners: [.bottomLeft, .bottomRight], radius: 10.0)
cell.layoutSubviews()
cell.layoutIfNeeded()

Extension which I am using:

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 need output like this:

enter image description here

Upvotes: 2

Views: 950

Answers (1)

Razi Tiwana
Razi Tiwana

Reputation: 1435

I had a similar problem a while back and what i was missing was that the table view is reusing the cells so we have to revert all the other cells to their default state.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! myCell

    let isFirstCell = indexPath.row == 0
    let isLastCell = indexPath.row == TotalRowsCount - 1

    if isFirstCell && isLastCell {
        cell.viewMain.topBottomRounded()
    } else if isFirstCell {
        cell.viewMain.topRounded()
    } else if isLastCell {
        cell.viewMain.bottomRounded()
    } else {
        // THIS IS THE KEY THING
        cell.viewMain.defaultStateForBorders()
    }

    return cell
}

I have run your Code and its working fine except this thing.

where helping methods using your extension method are:

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
}

func topRounded() {
    self.roundCorners(corners: [.topLeft, .topRight], radius: 10.0)
}

func bottomRounded() {
    self.roundCorners(corners: [.bottomLeft, .bottomRight], radius: 10.0)
}

func topBottomRounded() {
    self.roundCorners(corners: [.topLeft, .topRight,.bottomLeft, .bottomRight], radius: 10.0)
}

func defaultStateForBorders() {
    self.roundCorners(corners: [], radius: 0)
}

}

enter image description here

Upvotes: 3

Related Questions