1

TableView我在 iOS 中有一个支持 a 的文本数组。在cellForRowAtIndexPath: 方法中,我返回一个 UITableViewCell* ,其中填充了来自支持数组的文本。indexPath 用作后备数组的索引。

我现在想在最后一个单元格中添加一个“完成”按钮TableView。在我的 StoryBoard 中,我创建了第二个(原型)TableView Cell并给它一个标识符“ButtonCell”。我还在后备数组的末尾添加了一个额外的元素,因此 numberOfRowsInSection: 可以返回后备数组的计数,一切都会正常工作。

我想我会将最后一个数组元素的文本设置为 @"donebutton" 之类的东西,然后我可以在 cellForRowAtIndexPath: 中检查它。如果它是真的,我会知道我在我的数组的末尾并返回“ButtonCell”单元而不是正常的“Cell”。问题是,它不太正常。实现这一目标的最佳方法是什么?代码片段如下。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

   static NSString *ButtonCellIdentifier = @"ButtonCell";
   UITableViewCell *bcell = [tableView dequeueReusableCellWithIdentifier:ButtonCellIdentifier forIndexPath:indexPath];

   NSString *rowtext = [_mArCellData objectAtIndex:indexPath.row];

   // return button cell if last item in list
   if ([rowtext isEqualToString:[NSString stringWithFormat:@"%d", SUBMIT_BUTTON]])
   {
      NSLog(@"hit last row, so using button row");
      return bcell;
   }

   cell.textLabel.text = rowtext;
   return cell;
}

这就是我得到的

4

2 回答 2

3
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    static NSString *ButtonCellIdentifier = @"ButtonCell";

    UITableViewCell *cell;

    if (indexPath.row != ([_mArCellData count] - 1) { // if not the last row

        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        // configure cell...

    } else { // last row

        cell = [tableView dequeueReusableCellWithIdentifier:ButtonCell];
        // configure button cell...
    }

    return cell;
}
于 2013-10-01T20:04:36.150 回答
1

我只想将您的 if 语句更改为:

if ([tableView numberOfRowsInSection:0] == indexPath.row + 1) {
   NSLog(@"hit last row, so using button row");
   bcell.textLabel.text = rowtext;
   return bcell;
}

这比您的解决方案更抽象一点,并且不依赖于将单元格的属性设置为特定的任何内容。我喜欢@bilobatum 在 if 语句中调用 dequeueReusableCellWithIdentifier: 的方式。这也应该节省一些内存。

编辑:我还注意到您正在设置单元格文本,而不是 bcell 文本。

于 2013-10-01T20:11:09.990 回答