Search code examples
macoscocoacore-animationnstableview

How to scroll to row added to NSTableView after animation has finished


After adding a new row to an NSTableView I'd like to scroll to it.

When that row has been added to the end of table the scroll only scrolls to the row that was previously the last row. I initially thought that I had to wait for the animation to finish, but that hadn't solved my issue. Here's my code:

        [NSAnimationContext beginGrouping];
        [_tableView insertRowsAtIndexes:indexSet withAnimation:NSTableViewAnimationEffectGap];
        [[NSAnimationContext currentContext] setCompletionHandler:^{

            // Scroll to the first inserted row

            NSUInteger firstIndex = [indexSet firstIndex];
            [_tableView scrollRowToVisible:firstIndex];

        }];
        [NSAnimationContext endGrouping];

How can I do this?


Solution

  • I found a solution to his problem that I'm happy with:

    [_tableView insertRowsAtIndexes:indexSet withAnimation:NSTableViewAnimationEffectGap];
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        NSUInteger firstIndex = [indexSet firstIndex];
        [_tableView scrollRowToVisible:firstIndex];
    }];
    

    I'm simply delaying the scroll request until the next run loop.