美文网首页Collection view
给TableView的Section区域添加圆角

给TableView的Section区域添加圆角

作者: championfu | 来源:发表于2019-11-12 15:44 被阅读0次

    一行代码给section添加圆角(Swift)

    
    import UIKit
    
    extension UITableViewCell {
        
        private func _tableView() -> UITableView? {
            if let tableView = self.superview as? UITableView {
                return tableView
            }
            if let tableView = self.superview?.superview as? UITableView {
                return tableView
            }
            return nil
        }
        
        func addSectionCorner(at indexPath: IndexPath, radius: CGFloat = 10) {
            let tableView = self._tableView()!
            let rows = tableView.numberOfRows(inSection: indexPath.section)
            if indexPath.row == 0 || indexPath.row == rows - 1 {
                var corner: UIRectCorner
                if rows == 1 {
                    corner = UIRectCorner.allCorners
                }else if indexPath.row == 0 {
                    let cornerRawValue = UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue
                    corner = UIRectCorner(rawValue: cornerRawValue)
                }else {
                    let cornerRawValue = UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue
                    corner = UIRectCorner(rawValue: cornerRawValue)
                }
                let cornerLayer = CAShapeLayer()
                cornerLayer.masksToBounds = true
                cornerLayer.frame = self.bounds
                let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: radius, height: radius))
                cornerLayer.path = path.cgPath
                self.layer.mask = cornerLayer
            }else {
                self.layer.mask = nil
            }
        }
        
    }
    
    

    在UITableViewDelegate的willDisplayCell中调用即可

    相关文章

      网友评论

        本文标题:给TableView的Section区域添加圆角

        本文链接:https://www.haomeiwen.com/subject/ctlqictx.html