Swift中如何在UITableView的行之间插入独立的View视图块
实现方案
你可以通过给UITableView新增一行特殊的蓝色块cell来实现需求,具体修改如下:
1. 先在Storyboard中准备蓝色块的cell原型
在当前UITableView的原型cell区域新增一个UITableViewCell,设置复用ID为BlueBlockCell,将cell背景设为你需要的蓝色,清空默认的子视图即可。
2. 调整原有数据源和代理逻辑
修改对应代码如下:
import UIKit class ViewController: UIViewController , UITableViewDataSource, UITableViewDelegate { // 普通cell高度,根据你的实际需求修改 let normalCellHeight: CGFloat = 60 // 蓝色块高度,根据设计图修改 let blueBlockHeight: CGFloat = 40 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 原有5行+1行蓝色块,共6行 return 6 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 第3个普通cell之后是第4个位置,对应索引为3(从0开始计数) if indexPath.row == 3 { let blueCell = tableView.dequeueReusableCell(withIdentifier: "BlueBlockCell", for: indexPath) // 不需要点击效果的话可以加上这行 blueCell.selectionStyle = .none return blueCell } let cell = tableView.dequeueReusableCell(withIdentifier: "BidCell", for: indexPath) // 偏移行号,匹配你原有5个静态cell的顺序 let originalRow = indexPath.row < 3 ? indexPath.row : indexPath.row - 1 // 这里原有给cell赋值静态数据的逻辑保持不变,用originalRow取对应数据即可 return cell } // 如果蓝色块高度和普通cell不一致,实现该代理方法 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 3 { return blueBlockHeight } return normalCellHeight } }
可选替代方案
如果你不想修改原有行号逻辑,也可以把UITableView拆为2个section:第一个section放前3个普通cell,把第一个section的footerView设置为蓝色View,第二个section放剩下的2个普通cell,不需要额外新增cell原型。
内容的提问来源于stack exchange,提问作者User123
相关产品推荐
相关产品推荐

