哪个用?委托与keyPathObserver - UIViewController有两个UIScrollViews

时间:2017-07-06 22:33:25

标签: ios swift uiscrollview delegates

在我实现这个目标之前,我想知道在UIScrollView被移动时实现与contentOffest有关的最佳方法是什么。

注意:要求读取有多个对象调用委托方法可能会有问题

1)为每个视图的contentOffset keyPaths

添加观察者

2)使我的类成为UIScrollViewDelegate并使用scrollViewDidScroll

class MyAwesomeVC: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var scrollViewA: UIScrollView!
@IBOutlet weak var scrollViewB: UIScrollView!
private var observerContext = 0

...

     override func viewDidLoad() {
         super.viewDidLoad()

         scrollViewA.delegate = self
         scrollViewB.delegate = self

         scrollViewA.addObserver(self, forKeyPath: "contentOffset", options: .new, context: &observerContext)
         scrollViewB.addObserver(self, forKeyPath: "contentOffset", options: .new, context: &observerContext)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        // check which scrollview if possible then do all the things

    }


    func scrollViewDidScroll(_ scrollView: UIScrollView) {

                 // check which scrollview if possible then do all the things

    }

    ...
    deinit {
        scrollViewA.removeObserver(self, forKeyPath: "contentOffset", context: &observerContext)
        scrollViewB.removeObserver(self, forKeyPath: "contentOffset", context: &observerContext)
        scrollViewA = nil
        scrollViewB = nil
    }


}

1 个答案:

答案 0 :(得分:0)

我要说最简洁的方法是将自己指定为滚动视图委托并覆盖函数scrollViewDidScroll,并在函数中使用print(scrollView.contentOffset),并执行任何操作需要它。如果您需要检查是否向下滚动,可以将属性附加到您的类,以保存您的上一个contentOffset,并将其与当前内容进行比较。