如何按每3个Cell1后显示Cell2的模式展示TableView自定义Cell?
嘿,这个排列逻辑其实很好实现,咱们一步步来搞定它:
核心思路拆解
已知Cell1的总数据量,每3个Cell1之后插入1个Cell2,直到Cell1全部展示完毕。关键是要计算总行数,以及判断每个位置该显示哪种Cell。
具体代码实现
首先在你的ViewController里声明一个变量存储Cell1的总数据量:
@property (nonatomic, assign) NSInteger cell1TotalCount; // 你已知的Cell1数据总数
1. 返回总行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // 计算Cell2的数量:每3个Cell1对应1个Cell2,整数除法自动取整 NSInteger cell2Count = self.cell1TotalCount / 3; // 总行数 = Cell1总数 + Cell2数量 return self.cell1TotalCount + cell2Count; }
2. 复用并配置Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSInteger currentRow = indexPath.row; // 判断当前行是否是Cell2的位置:每4行的第4个位置(索引从0开始,所以用currentRow+1模4判断) if ((currentRow + 1) % 4 == 0) { Cell2 *cell2 = [tableView dequeueReusableCellWithIdentifier:@"Cell2ID" forIndexPath:indexPath]; // 这里根据需要配置Cell2的内容 return cell2; } else { // 计算当前Cell1对应的数据源索引:减去前面已经出现的Cell2数量 NSInteger cell2CountBefore = currentRow / 4; NSInteger cell1DataIndex = currentRow - cell2CountBefore; Cell1 *cell1 = [tableView dequeueReusableCellWithIdentifier:@"Cell1ID" forIndexPath:indexPath]; // 用cell1DataIndex获取对应的数据,比如: // cell1.contentLabel.text = self.cell1DataArray[cell1DataIndex]; return cell1; } }
3. 别忘了注册Cell复用标识符
在viewDidLoad里提前注册你的自定义Cell:
- (void)viewDidLoad { [super viewDidLoad]; // 注册Cell(如果用xib的话) [self.tableView registerNib:[UINib nibWithNibName:@"Cell1" bundle:nil] forCellReuseIdentifier:@"Cell1ID"]; [self.tableView registerNib:[UINib nibWithNibName:@"Cell2" bundle:nil] forCellReuseIdentifier:@"Cell2ID"]; // 赋值Cell1的总数据量,比如self.cell1TotalCount = self.cell1DataArray.count; }
额外说明
如果Cell1的总数不是3的倍数(比如4个),最终排列会是Cell1、Cell1、Cell1、Cell2、Cell1,完全符合你“每3个Cell1后加一个Cell2”的需求,剩下的不足3个的Cell1会直接展示,不会额外添加Cell2。
内容的提问来源于stack exchange,提问作者Tejas Patel
相关产品推荐
相关产品推荐

