美文网首页
iOS UITableView 添加Section圆角

iOS UITableView 添加Section圆角

作者: 麦志超 | 来源:发表于2022-12-19 15:08 被阅读0次

    1、扩展 UITableViewCell

    extension UITableViewCell {
        
        private func getTableView() -> 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.getTableView()!
            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
            }
        }
    }
    

    2、在 willDisplay 调用

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.addSectionCorner(at: indexPath, radius: 16)
    }
    

    相关文章

      网友评论

          本文标题:iOS UITableView 添加Section圆角

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