UITableViewCell设置最初select

嗨,我有情况,在一个iPad应用程序我的master controller列表和细节控制器有它的细节,一个典型的UISplitViewController模式。 我想实现的是,我的第一行应该是最初select,后来我想给用户selectselect。 我正在使用单元格的setSelecteddidSelectRowAtIndexPath方法删除这样的select。

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:NO]; NSIndexPath* path = [NSIndexPath indexPathForRow:0 inSection:0]; UITableViewCell* cell = [tableView cellForRowAtIndexPath:path]; [cell setSelected:NO]; } 

对于初始细胞,但我没有细胞被选中后,请帮助我。

尝试这个

 NSIndexPath* selectedCellIndexPath= [NSIndexPath indexPathForRow:0 inSection:0]; [self tableView:tableViewList didSelectRowAtIndexPath:selectedCellIndexPath]; [tableViewList selectRowAtIndexPath:selectedCellIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone]; 

要么

 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { if (/* should be selected */) { [cell setSelected:YES animated:NO]; } } 

为了显示选中的单元格,您必须从-tableView:willDisplayCell:forRowAtIndexPath:调用-setSelected:animated: -tableView:willDisplayCell:forRowAtIndexPath:所示:

 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { if (/* should be selected */) { [cell setSelected:YES animated:NO]; } } 

从任何其他地方select的调用都不起作用。

Swift 3:最初select单元格

 import UIKit class MyViewController: UIViewController, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! ... func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if /* your code here */ == indexPath.row { tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none) } } ... } 

我不知道你期待这个答案。 默认情况下,如果你想在你的tableView中select第一行而没有手动select,只需启动didSelectRowAtIndexPath方法

 - (void)viewDidAppear:(BOOL)animated { NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0]; [myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom]; } 

这也将有助于在POP导航的情况下

.h文件,

 NSIndexPath *defaultSelectedCell 

.m文件

把这个代码放在ViewDidLoad

 defaultSelectedCell= [NSIndexPath indexPathForRow:0 inSection:0]; 

viewDidAppear

 [self.tableView selectRowAtIndexPath:defaultSelectedCell animated:NO scrollPosition:UITableViewScrollPositionNone]; 

这将有助于当你的POP,把这个代码在viewWillAppear

 [self.catTableView selectRowAtIndexPath:defaultSelectedCell animated:NO scrollPosition:UITableViewScrollPositionNone]; 

tableView didSelectRowAtIndexPath方法中,

 defaultSelectedCell = [NSIndexPath indexPathForRow:indexPath.row inSection:0]; 

这可以帮助我完美的第一次加载或stream行导航。