How to determine if a user has scrolled to the end

2019-01-22 16:01发布

问题:

I have an NSTableView, and I would like to know when the user has scrolled to the bottom, so I can perform an action. Not quite sure how to go about this?

UPDATE: Here is how I am calculating the bottom of the table:

-(void)tableViewDidScroll:(CPNotification) notification
{
    var scrollView = [notification object];
    var currentPosition = CGRectGetMaxY([scrollView visibleRect]);
    var tableViewHeight = [messagesTableView bounds].size.height - 100;

    //console.log("TableView Height: " + tableViewHeight);
    //console.log("Current Position: " + currentPosition);

    if (currentPosition > tableViewHeight - 100)
    {
       console.log("we're at the bottom!");
    }
}

回答1:

You can add yourself as an observer (in the NSNotificationCenter sense, not the KVO/Bindings sense) of NSViewBoundsDidChangeNotification from the table's -enclosingScrollView's -contentView and react as necessary based on the visible rectangle.

Update

Do this somewhere (maybe -awakeFromNib):

// Configure the scroll view to send frame change notifications
id clipView = [[tableView enclosingScrollView] contentView];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(myBoundsChangeNotificationHandler:)
                                             name:NSViewBoundsDidChangeNotification
                                           object:clipView];

Put this somewhere useful:

- (void)myBoundsChangeNotificationHandler:(NSNotification *)aNotification
{

if ([aNotification object] == [[tableView enclosingScrollView] contentView])
    [self doSomethingInterestingIfDocumentVisibleRectSatisfiesMe];

}

Essentially you want to examine the scroll view's -documentVisibleRect to see if maybe the bottom couple of pixels are visible. Remember to account for the possibility of views with flipped coordinate systems - "flipped views" - covered in the Views Programming Guide.



回答2:

Regarding your update: for some reasons i have var currentPosition = CGRectGetMaxY([scrollView visibleRect]); always the same value, i've found better to use NSClipView bounds:

NSClipView *clipView = ...;
NSRect newClipBounds = [clipView bounds];
CGFloat currentPosition = newClipBounds.origin.y + newClipBounds.size.height;