Is it possible to add observer to tableView.contentOffset?

落爺英雄遲暮 提交于 2019-12-10 04:10:03

问题


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?


回答1:


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];



回答2:


Swift 5

tableContentObserver = table.observe(\UITableView.contentOffset, options: .new) { [weak self] table, change in
    self?.navigationItem.rightBarButtonItem?.title = "\(change.newValue)"
}



回答3:


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
    }
  }


来源:https://stackoverflow.com/questions/12087848/is-it-possible-to-add-observer-to-tableview-contentoffset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!