【问题标题】:Correctly Grab the IndexPath.row of a UIButton in Custom Table Cell?在自定义表格单元格中正确抓取 UIButton 的 IndexPath.row?
【发布时间】:2012-06-01 10:19:06
【问题描述】:

我有一个表格视图,可以从网络加载信息,并将其显示在自定义单元格中。在这些自定义单元格中,我有一个通过情节提要分配的按钮。

如果这个按钮被按下,它会触发一个方法(在 cellForRowAtIndexPath 方法中定义)

cell.viewArticleButton.action = @selector(viewArticle:); 

正是在这种方法中,我遇到了麻烦。该操作有效,只是它不使用为每个相应单元格提供的链接(每个索引路径处的链接),而是仅使用第一行的链接,无论我点击哪一行。

-(IBAction)viewArticle:(id)sender {

NSLog(@"View Article Button Tapped");

NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"];

NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 

MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];

   // Open link from item.link

}

任何帮助将不胜感激。我有一种感觉,就是这条线没有做我想要的:

NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"];

【问题讨论】:

    标签: iphone ios ios5 uitableview


    【解决方案1】:

    用这一行:

    NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
    

    您正在获得对原型(或模板)单元格的引用。这不会让您唯一地标识表格视图中的单元格。那只能识别从这个原型单元创建的一组单元。这就是为什么您总是获得第一行的原因;它返回使用此原型创建的第一个单元格。如果您只有一个具有标识符 @"NewsCell" 的单元格(其他单元格具有不同的标识符),那么您的实现就可以工作。

    要唯一标识您单击的单元格,请关注以下主题:Detecting which UIButton was pressed in a UITableView

    【讨论】:

      【解决方案2】:

      为什么不将 NSIndexPath 中的 add 添加到方法中:

      cell.viewArticleButton.action = @selector(viewArticle:indexPath);
      
      -(IBAction)viewArticle:(id)sender {
      NSIndexPath *indexPath = (NSIndexPath *)sender;
      
      NSLog(@"View Article Button Tapped for section %d, row $d", indexPath.section, indexPath.row);
      
      // I have no idea why you are doing this...
      NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
      
      
      MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
      
         // Open link from item.link
      
      }
      

      【讨论】:

      • 我已经尝试过这种方法,但我一直收到错误消息:“ -[UIBarButtonItem row]: unrecognized selector sent to instance 0x3488c0”
      • 我如何在 Swift 中做到这一点?
      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多