繁体   English   中英

如何向ios TableView行添加按钮

[英]How to add a button to ios TableView row

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

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

我以为我会将最后一个数组元素的文本设置为@“donebutton”,然后我可以在cellForRowAtIndexPath中检查它: 如果它出现了,我会知道我在数组的末尾并返回“ButtonCell”单元格而不是正常的“单元格”。 事情是,它不是很正常。 实现这一目标的最佳方法是什么? 代码片段如下。

- (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;
}

这就是我得到的

- (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;
}

我只想将你的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:call的方式。 这也应该节省一些内存。

编辑:我也注意到你正在设置单元格文本,但不是bcell文本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM