cocoanstableviewnsscrollviewnsscroller

Detecting Vertical NSScroller hitting bottom in NSTableView


Let's Say i loaded 100 rows in a table in awakeFromNib: , Now i want to call a method when the vertical scroller hits the bottom. Could anyone let me know how to handle the event of NSScroller hitting the bottom and calling a method when this happens.


Solution

  • // In awakeFromNib:
    self.scrollView = [self.tableView enclosingScrollView];
    
    // Register delegate to the scrollView content View:
    // This will send notification whenever scrollView content view visible frame changes.
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(scrollViewDidScroll:) name:NSViewBoundsDidChangeNotification object:self.scrollView.contentView];
    
    // This Method is called when content view frame changed
    - (void)scrollViewDidScroll:(NSNotification *)notification {
        NSScrollView *scrollView = self.scrollView;
        // Test if bottom of content view is reached.
        CGFloat currentPosition = CGRectGetMaxY([scrollView visibleRect]);
        CGFloat contentHeight = [self.tableView bounds].size.height - 5;
    
        if (currentPosition > contentHeight - 2.0) {
            // YOUR ACTION
        }
    }
    // Remove observer
    - (void)dealloc {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }