【问题标题】:UITableViewCell Rounded Corners Not Visible for Some CellsUITableViewCell 圆角对于某些单元格不可见
【发布时间】:2021-04-17 21:56:57
【问题描述】:

我的表格使用圆角单元格作为部分。但是,在某些 iOS 设备上,右侧的圆角是不可见的。这可能不太可能与代码相关,而更多地与约束有关。

下面的屏幕截图显示了圆角工作的地方(绿色框)和失败的地方(红色框)

我尝试了以下代码来添加圆角,看起来效果很好:

let path = UIBezierPath(roundedRect: cell.bounds,
           byRoundingCorners:[.topRight, .topLeft], // example
           cornerRadii: CGSize(width: 15, height:  15))
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
cell.layer.mask = maskLayer

我的单元格是这样初始化的,我在添加内容时没有调整它的大小:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "mycell")

我感觉添加到单元格的内容会推动隐藏圆角的单元格宽度。有什么想法可能是错的吗?

【问题讨论】:

    标签: ios swift iphone uitableview uibezierpath


    【解决方案1】:

    您需要继承 UITableViewCell 并覆盖layoutSubview() 函数并在那里设置CAShapeLayer 的路径。

    final class MyTableViewCell: UITableViewCell {
    
        private lazy var maskLayer = CAShapeLayer()
    
        var corners: UIRectCorner = [] {
            didSet {
                setNeedsLayout()
                updatePath(with: corners)
            }
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            updatePath(with: corners)
        }
    
        private func updatePath(with corners: UIRectCorner) {
            let path = UIBezierPath(
                roundedRect: bounds,
                byRoundingCorners: corners,
                cornerRadii: CGSize(width: 15, height:  15)
            )
            maskLayer.path = path.cgPath
            layer.mask = maskLayer
        }
    
    }
    

    然后通过cellForRowAt中的角

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = MyTableViewCell(
            style: UITableViewCell.CellStyle.default, reuseIdentifier: "mycell"
        )
        cell.corners = [.topRight, .topLeft]
    
        // ...
    
        return cell
    }
    
    

    【讨论】:

    • 为什么需要在UITableViewCelllayoutSubviews方法中设置CAShapeLayer的路径,而不是直接放在UITableViewControllercellForRowAt方法中?跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多