【发布时间】:2022-10-24 06:12:51
【问题描述】:
当调用reloadData 时,我对我的UITableViewCell 发生的事情感到非常困惑。当 tableview 首次加载时,每个单元格都有正确的舍入。顶部的顶角是圆形的,中间没有圆形,底部只有底部。
如果调用 tableview.reloadData(1 次或多次)会发生以下情况
这是创建单元格的代码(in func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath))
guard let cell = tableView.dequeueReusableCell(withIdentifier: MyCell().reuseIdentifier, for: indexPath) as? MyCell else { return UITableViewCell() }
if indexPath.row == 0 {
cell.roundCorners(corners: (top: true, bottom: false))
}
if indexPath.row == 1 {
cell.roundCorners(corners: (top: false, bottom: false))
}
if indexPath.row == 2 {
cell.roundCorners(corners: (top: false, bottom: true))
}
这是圆角的代码:
func roundCorners(corners: (top: Bool, bottom: Bool)) {
if !corners.top && !corners.bottom {
roundCorners(withRadius: 0)
} else if corners.top && corners.bottom {
roundCorners(withRadius: 20)
} else if corners.top {
roundCorners(corners: [.topLeft, .topRight], radius: 20)
} else if corners.bottom {
roundCorners(corners: [.bottomLeft, .bottomRight], radius: 20)
}
}
// and the actual rounding methods
func roundCorners() {
roundCorners(withRadius: bounds.size.height * 0.5)
}
func roundCorners(withRadius radius: CGFloat) {
layer.cornerRadius = radius
layer.masksToBounds = true
}
func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
func maskedCorners(withRadius radius: CGFloat) {
layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]
layer.cornerRadius = radius
clipsToBounds = true
}
func maskedCorners(corners: CACornerMask, radius: CGFloat) {
layer.maskedCorners = corners
layer.cornerRadius = radius
clipsToBounds = true
}
我尝试了几件没有用的事情。
-
我没有重用单元格(我认为可能重用它们的方式是在使用绘图调用),而是尝试每次都实例化单元格
-
我尝试将单元格边框重置为 0,然后设置哪些角应该是圆角的
-
我尝试在更新边框后调用 .setNeedsDisplay()
我还要注意,如果我注释掉舍入调用,则根本不会发生舍入,因此该问题与上面的代码严格隔离。
非常愿意接受关于为什么在第一次 reloadData() 调用它之后会围绕中间单元格并保持它向前移动的建议。
【问题讨论】:
-
我用自定义单元尝试了这个,即使在 reloadData 之后它也可以工作。
标签: ios swift uitableview