2014-11-06 67 views
0

我有表单元格;每个单元包含带有电话号码的标签。当我点击标签时,出现UIMenuController按标签查找单元格的索引路径

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

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

UPD

我有参考选择的标签。

+0

嗨,为什么不应该调用SelectRowAtIndexPath? – james075 2014-11-06 21:49:33

+0

对于拳头,我不会选择行时触摸标签,第二,在这种方法中,我可以只存储indexPath,作为参数。 @ James03 – 2014-11-06 21:52:46

回答

4

编辑:

这是一个更好的方法。

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

很容易!请告诉我,为什么.superview打了两次电话? – 2014-11-06 21:54:16

+0

contentView在iOS 7中存在tableViewCells – 2014-11-06 21:55:50

+0

在包含发件人和完成的IBAction方法中执行编辑后的答案。更干净。 – 2014-11-06 21:58:03

-1

你可以去:

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]; 
    } 
} 
+0

我知道这个算法,但我应该扫描整个表,那吓唬我(因为O(n))。 – 2014-11-06 21:56:35

+1

您可以使用UITableView方法 indexPathsForVisibleRows避免O(n)问题,然后检查该列表,但使用UITableView方法indexPathForRowAtPoint:,如DCGoD的答案中所述,更清晰和更简单。 – 2014-11-06 23:42:53

1

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

-(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使你的代码更强大,因为它通过系统的版本来处理单元视图层次结构中可能发生的变化。

+0

使用UITableView方法'indexPathForRowAtPoint:',如DCGoD的答案中所述,更清洁和更简单。 – 2014-11-06 23:42:18