Skip to content

Instantly share code, notes, and snippets.

@kgn
Created January 4, 2012 05:37
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgn/1558664 to your computer and use it in GitHub Desktop.
Save kgn/1558664 to your computer and use it in GitHub Desktop.
Animated NSTableView Scrolling
// Thanks to CuriousKea for getting this started!
// http://stackoverflow.com/a/8480325/239380
- (void)scrollRowToVisible:(NSInteger)rowIndex animate:(BOOL)animate{
if(animate){
NSRect rowRect = [self rectOfRow:rowIndex];
NSPoint scrollOrigin = rowRect.origin;
NSClipView *clipView = (NSClipView *)[self superview];
scrollOrigin.y += MAX(0, round((NSHeight(rowRect)-NSHeight(clipView.frame))*0.5f));
NSScrollView *scrollView = (NSScrollView *)[clipView superview];
if([scrollView respondsToSelector:@selector(flashScrollers)]){
[scrollView flashScrollers];
}
[[clipView animator] setBoundsOrigin:scrollOrigin];
}else{
[self scrollRowToVisible:rowIndex];
}
}
@adeperio
Copy link

adeperio commented Feb 25, 2016

Thanks! This was helpful - below is the swift version :)

`func scrollRowToVisible(row: Int, animated: Bool) {

    if(animated){


        let rowRect = self.rectOfRow(row)
        var scrollOrigin = rowRect.origin
        let clipView = self.superview as? NSClipView

        let tableHalfHeight = NSHeight(clipView!.frame)*0.5
        let rowRectHalfHeight = NSHeight(rowRect)*0.5

        scrollOrigin.y = (scrollOrigin.y - tableHalfHeight) + rowRectHalfHeight
        let scrollView = clipView!.superview as? NSScrollView

        if(scrollView!.respondsToSelector(#selector(NSScrollView.flashScrollers))){
            scrollView!.flashScrollers()
        }

        clipView!.animator().setBoundsOrigin(scrollOrigin)

    } else {

        self.scrollRowToVisible(row)
    }

}

`

@albbadia
Copy link

albbadia commented Jan 20, 2021

Swift 5.3 version

extension NSTableView {
    func scrollRowToVisible(row: Int, animated: Bool) {
        if animated {
            let rowRect = self.rect(ofRow: row)
            var scrollOrigin = rowRect.origin
            let clipView = self.superview as? NSClipView
            
            let tableHalfHeight = NSHeight(clipView!.frame)*0.5
            let rowRectHalfHeight = NSHeight(rowRect)*0.5
            
            scrollOrigin.y = (scrollOrigin.y - tableHalfHeight) + rowRectHalfHeight
            let scrollView = clipView!.superview as? NSScrollView
            
            if scrollView!.responds(to: #selector(NSScrollView.flashScrollers)) {
                scrollView!.flashScrollers()
            }
            
            clipView!.animator().setBoundsOrigin(scrollOrigin)
        } else {
            self.scrollRowToVisible(row)
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment