UITableView仅为顶部头部与底部单元格设置圆角的实现问题
嘿,我来帮你搞定这个UITableView圆角布局的问题!从你的描述来看,你想要实现的是section顶部header带左上、右上圆角,section最后一个cell带左下、右下圆角的卡片式布局,思路是对的,但几个细节没处理好导致圆角没生效,我帮你调整一下:
问题出在哪?
- 手动调用
layoutSubviews():这个方法是系统用来自动布局子视图的,你手动调用时,view的frame可能还没完全计算好,圆角自然无法正确显示。 - Cell未判断是否为最后一行:你现在给所有cell都加了底部圆角,这会导致每个cell都有圆角,而不是只有section的最后一个。
- 可能未开启
clipsToBounds:如果容器view没开启这个属性,圆角会被子视图覆盖,看起来像是没生效。
修正后的代码方案
1. 处理Section Header的圆角
把圆角设置放到headerCell的layoutSubviews()里(确保布局更新时圆角始终正确),同时开启clipsToBounds:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let headerView = tableView.dequeueReusableCell(withIdentifier: "headerCell") as? headerCell else { return UIView() } headerView.labelTaskName.text = arrayTaskLists[section].first?.outcome_title headerView.btnHeaderViewCell.tag = section headerView.delegate = self // 开启clipsToBounds,确保圆角生效 headerView.viewContainerHeader.clipsToBounds = true return headerView } // 在headerCell类里重写layoutSubviews,确保圆角随布局更新 class headerCell: UITableViewCell { @IBOutlet weak var viewContainerHeader: UIView! // ...其他IBOutlet override func layoutSubviews() { super.layoutSubviews() // 设置左上、右上圆角 viewContainerHeader.roundCorners([.topRight, .topLeft], radius: 10.0) } }
2. 处理Cell的圆角
只有当当前cell是section的最后一行时,才设置底部圆角,否则清除圆角:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.TaskInformationCell) as! TaskInformationCell // 获取当前section的总行数 let rowCount = tableView.numberOfRows(inSection: indexPath.section) // 判断是否为最后一行,针对性设置圆角 if indexPath.row == rowCount - 1 { cell.infoView.clipsToBounds = true cell.infoView.roundCorners([.bottomLeft, .bottomRight], radius: 10.0) } else { // 非最后一行,清除底部圆角 cell.infoView.roundCorners([.bottomLeft, .bottomRight], radius: 0.0) } return cell }
额外提示
确保你的roundCorners扩展方法是正确实现的(如果是自定义的),示例如下:
extension UIView { func roundCorners(_ corners: UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let maskLayer = CAShapeLayer() maskLayer.path = path.cgPath layer.mask = maskLayer } }
系统自带的layer.cornerRadius只能设置全部圆角,所以这个自定义扩展是实现局部圆角的必要条件。
这样调整后,你的section header和最后一个cell的圆角应该就能正常显示啦!
内容的提问来源于stack exchange,提问作者Anil Kukadeja
相关产品推荐
相关产品推荐

