如何为UITableView整组(含表头与单元格)添加圆角及背景(仿iOS天气APP)
实现UITableView整组(表头+单元格)圆角背景的方法
直接给表头和单元格单独加圆角容易出现缝隙,得配合调整样式,按下面的步骤修改你的代码即可:
1. 调整UITableView基础设置
在HomeViewController的viewDidLoad里添加以下配置:
tableView.backgroundColor = .clear // 把列表背景设为透明,避免遮挡组背景 tableView.separatorStyle = .none // 去掉单元格默认分割线 tableView.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16) // 给组添加边距,和iOS天气APP样式对齐
2. 修改表头视图样式
给HourlyForecastHeaderView设置顶部圆角,和单元格的底部圆角衔接:
class HourlyForecastHeaderView: UIView { override init(frame: CGRect) { super.init(frame: frame) setupStyle() } required init?(coder: NSCoder) { super.init(coder: coder) setupStyle() } private func setupStyle() { backgroundColor = .white // 替换成你需要的背景色,比如iOS天气的浅灰色 // 只保留左上角和右上角的圆角 layer.cornerRadius = 12 layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] layer.masksToBounds = true } }
3. 调整单元格样式
在cellForRowAt方法里,给单元格设置底部圆角,且和表头用相同背景色:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: HourlyForecastViewTableViewCell.identifier) else { return UITableViewCell() } // 统一背景色,避免默认样式干扰 cell.backgroundColor = .white cell.contentView.backgroundColor = .white // 只保留左下角和右下角的圆角 cell.layer.cornerRadius = 12 cell.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] cell.layer.masksToBounds = true // 确保contentView铺满单元格,避免出现缝隙 cell.contentView.frame = cell.bounds cell.contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] return cell }
4. 添加阴影(可选,还原iOS天气APP效果)
如果要实现和天气APP一致的阴影效果,直接给表头/单元格加阴影会出现断层,需要给整组套一个阴影容器:
添加以下代理方法:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { // 计算整组的总高度:表头高度 + 单元格高度 let sectionTotalHeight = tableView.sectionHeaderHeight + tableView.rowHeight // 创建阴影容器视图 let shadowView = UIView( frame: CGRect( x: tableView.sectionInset.left, y: view.frame.origin.y, width: tableView.bounds.width - tableView.sectionInset.left - tableView.sectionInset.right, height: sectionTotalHeight ) ) shadowView.backgroundColor = .white shadowView.layer.cornerRadius = 12 shadowView.layer.shadowColor = UIColor.black.cgColor shadowView.layer.shadowOpacity = 0.1 shadowView.layer.shadowOffset = CGSize(width: 0, height: 2) shadowView.layer.shadowRadius = 4 // 把阴影容器放在表头和单元格下方 tableView.insertSubview(shadowView, at: 0) // 把表头和单元格设为透明,让阴影容器显示出来 view.backgroundColor = .clear // 同步修改cellForRowAt里的cell.backgroundColor为.clear }
完成以上修改后,每个组的表头和单元格就会无缝衔接,呈现出和iOS天气APP一致的整组圆角背景效果。
内容的提问来源于stack exchange,提问作者Sahil Sahu
相关产品推荐
相关产品推荐

