2012-05-11 106 views
2

我有一个包含多个单元格的表格视图。当我添加一个新的单元格(使用模态视图控制器)时,我想向用户显示新添加的单元格。要做到这一点,我想滚动表格视图到新的单元格,选择它并立即取消选择它。将表格视图滚动到单元格,然后刷单元格

现在,我在固定的时间间隔后发送deselectRowAtIndexPath我的表视图:

- (IBAction)selectRow 
{ 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:7 inSection:0]; 
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop]; 
    [self performSelector:@selector(deselectRow:) withObject:indexPath afterDelay:1.0f]; 
} 

- (void)deselectRow:(NSIndexPath *)indexPath 
{ 
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; 
} 

我不知道是否有这样做一个更好的方式。它运行良好,但我不喜欢依靠静态定时器来执行有时会花费不同时间的操作(例如,如果表非常长)。

编辑:请注意,selectRowAtIndexPath:animated:scrollPosition不会导致UITableView委托方法被激发。 tableView:didSelectRowAtIndexPath:scrollViewDidEndDecelerating:都不会被调用。从文档:

调用此方法不会导致委托接收tableView:willSelectRowAtIndexPath:tableView:didSelectRowAtIndexPath:消息,也不会发送UITableViewSelectionDidChangeNotification通知观察员。

回答

0

UITableViewDelegateUIScrollViewDelegate的扩展。您可以实施UIScrollViewDelegate方法之一,并使用它来确定何时取消选择该行。 scrollViewDidEndDecelerating:似乎是一个很好的开始。

另外,我个人发现performSelector...方法由于1个参数限制限制。我更喜欢使用GCD。该代码是这样的:

- (IBAction)selectRow 
{ 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:7 inSection:0]; 
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop]; 
    //deselect the row after a delay 
    double delayInSeconds = 2.0; 
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); 
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
     [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; 
}); 

}

+0

感谢GCD的版本。不幸的是,滚动视图委托不会被通知,因为滚动不是用户启动的。我实现它来检查,但只有当我手动滚动表时调用它。 –

+0

您可以实现'scrollViewDidScroll:'并检查'contentOffset.y'来查看单元格是否可见。 –

相关问题