我如何select默认的UITableViewCell?
我已经创build了一个UITableView
并希望特定的UITableViewCell
在加载视图时出现select(蓝色)。
-(void)viewWillAppear:(BOOL)animated { // assuming you had the table view wired to IBOutlet myTableView // and that you wanted to select the first item in the first section [myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop]; }
我使用这种技术来select两个UITableViewCells
之一,以便用户知道哪个单元UIDatePicker
下面的表视图将影响。 在创build新事件并设置date时,苹果会在日历应用程序中使用此技术。
使用这种方法是明智的,因为用这种方式select行是苹果build议不要做的,以显示“select”状态。
相反,考虑将单元格的accessoryType
属性设置为像UITableViewCellAccessoryCheckmark
。
你应该把它放在viewWillAppear
。
[myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:0];
如果您尝试在cellForRowAtIndexPath:
select它,则不会采用所需的样式。
绝对要小心。 我相信你有一个很好的理由,但仔细看一下苹果提供的人机接口指南文档。 应用程序因拒绝select表格行而被拒绝。 我鼓励你findHIG的适当部分,并看到苹果提供任何build议。
使用此代码默认在表视图中select单元格, indexPath
可以根据您的需要而有所不同
-(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0]; [theTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom]; }
使用UITableViewCell方法
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
信息在这里 。
有时,当你不在UIViewController
,你没有viewWillAppear
,有时候,你以编程的方式创build了你的UITableView
。
简单的解决scheme是实现这个delegate
方法:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { if (self.selectedIndex == indexPath.row) { cell.selected = YES; } }
它在cellForRowAtIndexPath
不起作用,因为单元格尚未显示。 并且只有在显示这一个时才调用setSelected
方法。