如何以编程方式“点击”UITableView单元格?

21

我在想是否有一种方法可以让我的代码“轻触”UITableView中的单元格,以重现在- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath委托方法中指定的行为。

换句话说,是否有可能通过编程方式调用- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath委托方法?

5个回答

39

如果你想选择单元格,即高亮显示特定的单元格:

//select first row of first section
NSIndexPath* selectedCellIndexPath= [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:selectedCellIndexPath animated:false scrollPosition:UITableViewScrollPositionMiddle];

如果想在didSelectRowAtIndexPath方法中触发额外的操作,需要手动调用委托方法,不会自动发生:

[self tableView:self.tableView didSelectRowAtIndexPath:selectedCellIndexPath];

2
调用didSelectRowAtIndexPath并不会触发segue。 - pronebird
是的。对我有效。 - Robert J. Clegg

21

你可不可以将didSelectRowAtIndexPath中的逻辑放到一个单独的方法中,并从didSelectRowAtIndexPath和任何其他你想调用同一代码的地方调用那个方法?


1
是的,但是当您点击时,单元格不会像点击时那样突出显示。有什么想法吗? - Ethan Parker
1
@BeemerFan:直接从调用新的公共方法的方法中进行调用:[self.tableView selectRowAtIndexPath:myIndexPath animated:false scrollPosition:UITableViewScrollPositionNone]; - Rob

7

Swift 3.2 解决方案

let indexPath = IndexPath(row: 2, section: 0)  // change row and section according to you
tblView.selectRow(at: indexPath, animated: true)
tblView.delegate?.tableView!(tblView, didSelectRowAt: indexPath)

似乎是从这里获取的 https://dev59.com/7WMl5IYBdhLWcg3woYPa#40590050! - Nike Kov

2

这只是一个方法。您可以像调用其他方法一样调用它。


4
那其实是一个实例方法,不是类方法 - 但嘿,这可能有点苛求 :D。 - Till

1
这是一个6.1更新。当您使用转场时,所有建议都很好,但您还需要调用转场。因此,为了补充建议并总结它。
// ... assuming we just added a new row - which is one use of what this thread is trying to do

/* get new count - this is the row we are going to highlight - 0 based */
 int newIndex = [dataArrayUnderlyingTable count]-1; 

/* make it look pretty by highlighting it */
    NSIndexPath *nip = [NSIndexPath indexPathForRow:newIndex inSection:0];
    [[self tableView] selectRowAtIndexPath:nip animated:YES scrollPosition:UITableViewScrollPositionBottom];

/* run the code in the following method so it is not missed */
    [self tableView:[self tableView] didSelectRowAtIndexPath:nip];

/* now 'tap' on it ... or simulate it */
    [self performSegueWithIdentifier: @"viewChildDetails" sender: self];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接