如何以编程方式 select uitableview 单元格?

How to select a uitableview cell programmatically?

我有一个 UISearchController,我想 select 单击键盘上的搜索按钮时搜索结果控制器表视图的第一行。 为此,我尝试实施

-(void)searchButtonClicked:(UISerachBar*)searchBar {
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
  [self.searchResultsController.tableView selectRowAtIndexPath: indexPath animated:false scrollPostion:UITableViewScrollPositionNone];
  [self.searchResultsController tableview:self.searchResultsController.tableView didSelectRowAtIndexPath: indexPath];
 }

但它对我不起作用!!

然后我试着做了一个单独的方法:

-(void) plotPinOnMapWithIndexPath:(NSIndexPath*)indexpath;

并通过传递 indexPaths 在 didSelectRowAtIndexPathsearchButtonClicked 方法中调用它。But the problem is that the cell doesn't get highlighted the way it gets highlighted when user clicks on it.

这对我有用,而且是正确的:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath animated:NO     scrollPosition:UITableViewScrollPositionNone];

可以选择试试这个:

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

或者您可以使用 Segue 继续结果:

[self performSegueWithIdentifier:"showDetailView" sender:self];

在您传递参数的 prepareForSegue 方法中....

成功了!!

-(void)searchButtonClicked:(UISerachBar*)searchBar {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self tableview:self.searchResultsController.tableView didSelectRowAtIndexPath: indexPath];

}