如何用UIKit+Storyboard实现带层级圆角的TableView界面?
UIKit + Storyboard 实现嵌套布局与层级圆角方案
一、基础布局搭建
- 主容器使用UITableView,在Storyboard中拖入后设置全屏约束。
- 自定义TableViewCell,内部嵌入UICollectionView,给CollectionView添加上下左右约束(若需自适应高度,先设置预估高度,后续通过代码适配)。
- 在Storyboard中给自定义Cell、CollectionViewCell设置好重用ID,直接拖线关联数据源和代理到ViewController。
二、层级圆角实现
1. CollectionViewCell 分位置设置圆角
根据设计的层叠视觉效果,不同位置的Cell需要设置不同的圆角:
- 顶部Cell:仅裁剪左上角、右上角
- 底部Cell:仅裁剪左下角、右下角
- 单个Cell:四个角全部裁剪
- 中间Cell:无需裁剪圆角(被上下层遮挡)
在自定义CollectionViewCell中添加配置方法:
func setupCorner(isTop: Bool, isBottom: Bool, isSingle: Bool) { var targetCorners: UIRectCorner = [] if isSingle { targetCorners = [.topLeft, .topRight, .bottomLeft, .bottomRight] } else { if isTop { targetCorners = [.topLeft, .topRight] } else if isBottom { targetCorners = [.bottomLeft, .bottomRight] } } let cornerPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: targetCorners, cornerRadii: CGSize(width: 12, height: 12)) let maskLayer = CAShapeLayer() maskLayer.path = cornerPath.cgPath layer.mask = maskLayer // 显示阴影需同步设置shadowPath,避免阴影被mask裁剪 layer.shadowPath = cornerPath.cgPath layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.15 layer.shadowOffset = CGSize(width: 0, height: 3) layer.shadowRadius = 5 clipsToBounds = false }
在CollectionView的cellForItemAt方法中判断位置并调用配置:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourCellID", for: indexPath) as! CustomCollectionCell let totalItems = collectionView.numberOfItems(inSection: indexPath.section) let isTop = indexPath.item == 0 let isBottom = indexPath.item == totalItems - 1 let isSingle = totalItems == 1 cell.setupCorner(isTop: isTop, isBottom: isBottom, isSingle: isSingle) // 其他cell配置逻辑 return cell }
2. 顶部区域圆角处理
如果顶部是TableView的HeaderView:
- 自定义HeaderView,在
layoutSubviews中设置顶部圆角:
override func layoutSubviews() { super.layoutSubviews() let headerPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 12, height: 12)) let maskLayer = CAShapeLayer() maskLayer.path = headerPath.cgPath layer.mask = maskLayer }
如果顶部是TableView的第一个Cell,直接在该Cell的配置中设置顶部两个角的圆角即可,逻辑与CollectionViewCell的顶部圆角设置一致。
三、嵌套布局适配要点
- CollectionView高度自适应:
- 给CollectionView的FlowLayout设置
estimatedItemSize = UICollectionViewFlowLayout.automaticSize,让Cell自动适配内容。 - 自定义TableViewCell中实现高度自适应:
override func preferredLayoutAttributesFitting(_ layoutAttributes: UITableViewLayoutAttributes) -> UITableViewLayoutAttributes { let attrs = super.preferredLayoutAttributesFitting(layoutAttributes) layoutIfNeeded() attrs.frame.size.height = contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height return attrs } - 给CollectionView的FlowLayout设置
- 层级视觉优化:
- 给CollectionViewCell添加轻微阴影增强层叠感,需开启
clipsToBounds = false才能显示阴影。 - 可给TableViewCell之间设置小间距,让层叠效果更明显。
- 给CollectionViewCell添加轻微阴影增强层叠感,需开启
内容的提问来源于stack exchange,提问作者Jaseel.Dev
相关产品推荐
相关产品推荐

