Sukhpreet
Sukhpreet

Reputation: 943

Round upper corners for UITableView

I'm trying to round upper corners for UITableView. But Table view is not displaying. What is wrong here ?

// TableView setup

lazy var tableView: UITableView = {
        let tv = UITableView()
        tv.delegate = self
        tv.dataSource = self
        tv.separatorStyle = .none
        tv.backgroundColor = .white
        tv.layer.masksToBounds = true
        tv.roundUpperCorners(radius: 12)
        return tv
    }()

// Round upper corners.

 func roundUpperCorners(radius: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }

Upvotes: 1

Views: 1746

Answers (3)

iPatel
iPatel

Reputation: 47119

As per @Fahri Azimov comment you should set frame of your table view, first go with his comment. If still facing issue then use below code.

From my code,

myTblView.clipsToBounds = true
myTblView.layer.cornerRadius = 10 // Set As you want
myTblView.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]

NOTE : maskedCorners new in iOS 11 you can read from official document.

Upvotes: 6

Sukhpreet
Sukhpreet

Reputation: 943

It is working. Thanks to Fahri Azimov for mentioning "Try to round the corners after setting the table's frame".

I moved this line tableView.roundUpperCorners(radius: 12) into viewDidLayoutSubviews.

 override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        tableView.roundUpperCorners(radius: 12)
    }

Upvotes: 2

Sabarinathan Jayakodi
Sabarinathan Jayakodi

Reputation: 342

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

yourView.roundCorners([.topLeft,.topRight], radius: 5)

Upvotes: 3

Related Questions