用于滚动开始的KVO&在UIScrollView中结束

时间:2016-07-15 18:23:46

标签: ios swift uiscrollview

有没有办法在swift中使用KVO(键值观察)来检测 scrollViewWillBeginDragging scrollViewDidEndDecelerating

编辑:我试过了

scrollView.addObserver(self, forKeyPath: "dragging", options: NSKeyValueObservingOptions.New, context: nil)

但它从未被召唤过。如果我观察到例如" contentOffset"以同样的方式,它被称为。是否符合KVC标准?

3 个答案:

答案 0 :(得分:1)

我不确定这是否足以解决您的问题,但是虽然您可能无法直接观察isDragging或isDecelerating,但可以将它们作为观察contentOffset进行跟踪。要找到拖动的开始和结束,您可以通过创建全局布尔值(此处为draggingInitiated)并在您的watchValue中包含类似内容来简单地跟踪isDragging从false变为true以及从true变为true的时间:

if !draggingInitiated && scrollView.isDragging {
    draggingInitiated = true
    print("Started Dragging")
} else if draggingInitiated && !scrollView.isDragging {
    draggingInitiated = false
    print("Ended Dragging")
}

答案 1 :(得分:0)

基于@Philip De Vries的答案

快速5

  1. 添加观察者

    scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
    
  2. 观察

    // MARK: - Observation
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        if let obj = object as? UIScrollView {
          if obj == self.scrollView && keyPath == "contentOffset" {
    
            scrollViewDidScroll(scrollView)
    
            if !draggingInitiated && scrollView.isDragging {
              draggingInitiated = true
              onStartDraggin()
            } else if draggingInitiated && !scrollView.isDragging {
              draggingInitiated = false
              onReleaseDragging()
            }
          }
        }
      }
    
  3. 清理

    private func removeObsrvers() {
       scrollView.removeObserver(self, forKeyPath: "contentOffset")
    }
    

答案 2 :(得分:-1)

您可以使用NSNotification中心添加观察者。

在VC的viewDidLoad中,

   override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.informBeginDragging), name: "begin", object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.informEndDragging), name: "end", object: nil)

}

您可以使用以下两种方法执行任何操作

    func informBeginDragging() {
    //do something
}

func informEndDragging() {
    //do something
}

当滚动视图开始拖动或结束拖动时,将触发这两种方法

    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    NSNotificationCenter.defaultCenter().postNotificationName("end", object: nil)
}

func scrollViewWillBeginDragging(scrollView: UIScrollView) {
    NSNotificationCenter.defaultCenter().postNotificationName("begin", object: nil)
}