问题描述
我的表格对各个部分使用圆角单元格。但是,在某些 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
}