【问题标题】:Find indexPath of cell by label通过标签查找单元格的 indexPath
【发布时间】:2014-11-06 21:43:52
【问题描述】:

我有带有单元格的表格;每个单元格都包含带有电话号码的标签。当我点击标签时,UIMenuController 出现。

是否有一种主要的方法来查找包含选定标签的单元格的 indexPath? (didSelectRowAtIndexPath: 不应该被调用)

我可以想象许多肮脏的黑客,但我正在寻找一个主要/好的解决方案。

更新

我参考了选定的标签。

【问题讨论】:

  • 嗨,为什么不应该调用 didSelectRowAtIndexPath ?
  • 首先,我不会在触摸标签时选择行,其次,在这种方法中,我可以只存储 indexPath,它作为参数。 @James03

标签: ios objective-c uitableview


【解决方案1】:

编辑:

这是一个更好的方法。

- (IBAction)someMethod:(id)sender {
    CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tableView]; 
    NSIndexPath *hitIndex = [self.tableView indexPathForRowAtPoint:hitPoint];
}

【讨论】:

  • 很简单!请告诉我,为什么 .superview 调用了两次?
  • contentView 存在于 iOS 7 tableViewCells
  • 在包含发件人的 IBAction 方法中执行已编辑的答案并完成。干净多了。
  • 我本来打算这么建议的,但你抢先了。 (已投票)
【解决方案2】:

从您的标签中,搜索标签层次结构中的单元格对象:

-(UITableViewCell*) cellContainingView:(UIView*)view
{
    UIView* currentView = view;
    while (currentView)
    {
        if ([currentView isKindOfClass:[UITableViewCell class]])
        {
            return (UITableViewCell*)currentView;
        }
        currentView = currentView.superview;
    }
    return nil;
}

获得手机后,请致电[tableView indexPathForCell:cell] 使用这种方法而不是硬编码 view.superview.superview 使您的代码更强大,因为它可以通过系统版本处理单元格视图层次结构中可能发生的变化。

【讨论】:

  • 使用 UITableView 方法 indexPathForRowAtPoint:,如 DCGoD 的回答中所述,更简洁。
【解决方案3】:

你可以去:

NSMutableArray *cells = [[NSMutableArray alloc] init];
for (NSInteger j = 0; j < [tableView numberOfSections]; ++j)
{
    for (NSInteger i = 0; i < [tableView numberOfRowsInSection:j]; ++i)
    {
        [cells addObject:[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
    }
}

for (UITableViewCell *cell in cells){
   for (UILabel *label in cell.subviews){
        if (label == yourLabel)
           indexPath = [tableView indexPathForCell: cell];
   }
}

【讨论】:

  • 我知道这个算法,但我应该扫描整个表,这吓到我了(因为 O(n))。
  • 您可以使用 UITableView 方法 indexPathsForVisibleRows 避免 O(n) 问题,然后检查该列表,但使用 UITableView 方法 indexPathForRowAtPoint:,如 DCGoD 的回答中所述,更简洁。
猜你喜欢
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
  • 2020-12-02
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
相关资源
最近更新 更多