簡體   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