13

I need to track tableView.contentOffset.y Is it possible to add observer to tableView.contentOffset?

I think this is impossible because contentOffset doesn't inherit NSObject class.

Is any other solution?

Voloda2
  • 12,359
  • 18
  • 80
  • 130

3 Answers3

27

UITableView is a UIScrollView subclass so you can use the UIScrollViewDelegate method scrollViewDidScroll: to be notified when the view scrolled. Check the contentOffset of the scrollView in that method

contentOffset is a key path, so you can also observe its changes using KVO

[self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
wattson12
  • 11,176
  • 2
  • 32
  • 34
15

Swift 5

tableContentObserver = table.observe(\UITableView.contentOffset, options: .new) { [weak self] table, change in
    self?.navigationItem.rightBarButtonItem?.title = "\(change.newValue)"
}
Mike Glukhov
  • 1,758
  • 19
  • 18
6

Swift 3

Add an observer for the contentOffset key path using Key-Value Observing (KVO):

tableView.addObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset), options: [.old, .new], context: nil)

And handle notifications for changes:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == #keyPath(UIScrollView.contentOffset) {
      // Your code
    }
  }
César Cruz
  • 464
  • 4
  • 5