我的表格的各个部分使用圆角单元格。但是,在某些 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")
我有一种感觉,添加到单元格的内容会插入隐藏圆角的单元格宽度。有什么想法可能是错误的吗?
最佳答案
您需要子类化 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/