2012-06-20 10 views
7

新しいアイテムをUITableViewの下部に追加しています。アイテムを挿入した後、UITableViewを一番下までスクロールして、 。新しい項目はコアデータに保存され、UITableViewはNSFetchedResultsControllerを使用して自動的に更新されます。scrollToRowAtIndexPathを使用して最後にUITableViewCellにスクロールします。atScrollPosition:NSFetchedResultsControllerDelegateメソッドを使用してアニメーションを行います。

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject 
    atIndexPath:(NSIndexPath *)indexPath 
forChangeType:(NSFetchedResultsChangeType)type 
    newIndexPath:(NSIndexPath *)newIndexPath 
{ 
    switch (type) { 
    case NSFetchedResultsChangeInsert: 
     NSLog(@"*** controllerDidChangeObject - NSFetchedResultsChangeInsert"); 
     [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 

    //THIS IS THE CODE THAT DOESN'T WORK 
    [self.tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 

     break; 

    .... 
} 

これは境界外のエラーにつながります。私はそれを機能させるようには見えません。インデックスパスの行を調整して2番目のコメントまでスクロールすることはできますが、最後のアイテムには到達できません。

基本的には、コメントの表にコメントを追加しています。コメントが追加された後、その表を最新のコメントにスクロールします。この場合に役立ちます

答えて

16

を参照してください。シンプルなケースは次のようになります。あなたがNSFetchedResultsControllerを使用したよう

[self.tableView beginUpdates]; 
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
[self.tableView endUpdates]; 
[self.tableView scrollToRowAtIndexPath:insertedIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 

、呼び出しがbeginUpdatesinsertRowsAtIndexPaths:withRowAnimation:がそうであるように、それは、もう少し複雑であり、endUpdatesは異なるデリゲートメソッドで一般的です。あなたはその後、何ができることは、-controller:didChangeObject:atIndexPath:-insertRowsAtIndexPaths:withRowAnimation:コールの後に挿入されたインデックスパス

  • を保存-controllerDidChangeContent:[self.tableView endUpdates]

    self.insertedIndexPath = insertedIndexPath; 
    
  • を追加し、

    を追加するプロパティinsertedIndexPathを追加

    1. です
      if (self.insertedIndexPath) { 
          [self.tableView scrollToRowAtIndexPath:self.insertedIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 
          self.insertedIndexPath = nil; 
      } 
      
  • +0

    ありがとう@tammo!これは完全に機能しました! – djblue2009

    +0

    'newIndexPath'という名前のプロパティを作成すると、ビルドエラーが生成されます: '所有しているオブジェクトを返すためのCocoa命名規則に従います ' プロパティの名前をちょっと変えてください] –

    +0

    :Dこれはコンパイラこれについて不平を言っていませんでした。 'newIndexPath'を' insertedIndexPath'に変更します。 –

    0

    あなたはtableViewが新しいセクションと行を計算することができるようにendUpdatesを呼び出す必要があります...

    [self.tableView beginUpdates]; 
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    [self.tableView endUpdates]; 
    
    [self.tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 
    
    関連する問題