2015-10-27 87 views
0

所以我試圖預先使用selectRowAtIndexPath在表中選擇一行。使用selectRowAtIndexPath手動選擇UITableView中的行

我的問題是,哪裏是調用selectRowAtIndexPath的最佳位置?

我想調用這個的唯一地方是在cellForRowAtIndexPath:...因爲我有indexPath,但似乎沒有工作。

我欣賞任何答案或建議。

謝謝!

+0

'viewWillAppear:'將是一個共同的地方。 – rmaddy

回答

0

方法1

對於小區出現選擇,你必須調用-setSelected:animated:-tableView:willDisplayCell:forRowAtIndexPath:內,像這樣:

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

方法2

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

如果你想與特定的行是選擇每次然後方法1是更好的,否則,如果你只是想爲最初選擇然後方法2更好。

+0

啊,謝謝你,我的方法2是我正在尋找的! – Water4Fun

+0

很高興幫助! –

0

爲什麼不只是手動設置單元格,而不是調用委託方法?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath]; 
    //... 
    if(/* some condition */) { 
     cell.selected = YES; 
    } 
    //... 
    return cell; 
} 
相關問題