ios - UITableViewCell 圆角对于某些单元格不可见

标签 ios swift iphone uitableview uibezierpath

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

下面的屏幕截图显示了圆角起作用的地方(绿色框)和失效的地方(红色框) enter image description here

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

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")

我有一种感觉,添加到单元格的内容会插入隐藏圆角的单元格宽度。有什么想法可能是错误的吗?

最佳答案

您需要子类化 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
}

关于ios - UITableViewCell 圆角对于某些单元格不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65692590/

相关文章:

ios - 如何从另一个iOS应用程序打开Facebook应用程序设置?

ios - 如何在 iOS 中获取 SIM 卡漫游状态

ios - UISearchController.hidesNavigationBarDuringPresentation 在 iOS 11 Beta 中被 scopeButtons 忽略

ios - 使用多个 AVPlayer 时如何检测哪个视频结束了?

ios - UILabel 在动态创建的 UIView 上不可见

ios - NSLocalizedString - 线程 1 : EXEC_BAD_ACCESS with String. localizedStringWithFormat

iphone - 在 iPhone 开发中的反向地理编码器中获得奇怪的输出

ios - UIPrintInteractionController 不显示纸张选择

ios - iOS印度的任何网上银行SDK或api

iphone - 如何在 UIView 下绘制阴影?