如何默认选择UITableViewCell?

时间:2009-08-24 16:43:44

标签: iphone ios cocoa-touch uitableview

我创建了一个UITableView,并且希望在加载视图时显示选中的特定UITableViewCell(蓝色)。

7 个答案:

答案 0 :(得分:41)

-(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];
}

我正在使用此技术选择两个UITableViewCells中的一个,以便用户知道它将影响的表格视图下面的哪个单元格UIDatePicker。当您创建新事件并设置日期时,Apple会在日历应用中使用此技术。

答案 1 :(得分:6)

使用这种方法是明智的,因为以这种方式选择行是Apple suggests against做的事情,以显示“选择”状态。

相反,请考虑将单元格的accessoryType属性设置为UITableViewCellAccessoryCheckmark

答案 2 :(得分:3)

你应该把它放在viewWillAppear中。

[myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
                         animated:NO 
                   scrollPosition:0];

如果您尝试在cellForRowAtIndexPath:中选择它,那么它将不会采用所需的样式。

答案 3 :(得分:1)

绝对要小心。我确信你有充分的理由,但仔细看看Apple提供的人机界面指南文件。应用会因未取消选择表格行而被拒绝。我鼓励您找到HIG的相应部分,并看到Apple提供任何建议。

答案 4 :(得分:1)

默认情况下,在表格视图中使用此代码选择单元格,indexPath可根据需要而变化

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

答案 5 :(得分:0)

使用UITableViewCell方法

- (void)setSelected:(BOOL)selected animated:(BOOL)animated

信息here

答案 6 :(得分:0)

有时,当您不在UIViewController时,您没有viewWillAppear,有时您会以编程方式创建UITableView

简单的解决方案是实现此delegate方法:

- (void)tableView:(UITableView *)tableView 
        willDisplayCell:(UITableViewCell *)cell 
        forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.selectedIndex == indexPath.row) {
        cell.selected = YES;
    }
}

它在cellForRowAtIndexPath中不起作用,因为尚未显示该单元格。并且只有在显示此方法时才会调用setSelected方法。

相关问题