亲宝软件园·资讯

展开

Swift 监测页面滚动 Swift 使用 Observe 监测页面滚动的实现方法

jackpu 人气:0

Swift 以前是通过addObserver来实现对某个属性的变化监听,而最新的变化,书写起开更加方便。

observer = test.observe(\.field, options: [.new, .initial]) { (object, change) in
   print(change)
  }

一定要用属性赋值当前的 observe 结果,没有的话可能会造成 change 不生效。

对 UIScrollView 的滚动监听,我们可以使用UIScrollViewDelegate

extension UIScrollViewDelegate{
 func scrollViewDidScroll(scrollView: UIScrollView){
  //do something
 }
}

这里推荐使用 Observe 比较方便的是可以进行模块的逻辑的拆分,我们只需在自己的组件里面进行监听

class ComponetView: UIVIew {
	private var observation: NSKeyValueObservation?
	init(targetView: UIView) {
		observation = targetView.observe(\.contentOffset, options: [.new]) { [weak self] scrollView, change in
   // handle data contentOffset
  }
	}
}

附录:Swift中实现Observable机制

今天给别人讲个Observable的实现和使用场景,结合Observable-Swiftgithub:https://github.com/slazyk/Observable-Swift讲了半天貌似还没有特别明白,故写了个简易的实现,讲述了下Observable属性监控机制。

//: Playground - noun: a place where people can play

import UIKit
import Foundation

// MARK: - Observable
class Observable<T> {
  // 定义block结构
  typealias Observer = T -> Void

  // 申明一个block,用于数据改变的执行
  private var observer: Observer?

  // 数据发生变更,则通过observer告知
  var value: T {
    didSet {
      observer?(value)
    }
  }

  init(_ v: T) {
    value = v
  }

  func observe(observer: Observer?) {
    self.observer = observer
    observer?(value)
  }
}

// MARK: - People
struct PeopleModel {
  let firstName: Observable<String>
  let lastName: Observable<String>

  init(firstName: String, lastName: String) {
    self.firstName = Observable(firstName)
    self.lastName = Observable(lastName)
  }
}

// MARK: - Test

// test1
let people = PeopleModel(firstName: "sunny", lastName: "liu")
people.firstName.observe {
  newValue in
  print("firstName changed: \(newValue)")
}
people.lastName.observe {
  print("lastName changed: \($0)")
}
people.firstName.value = "sunny2"
people.lastName.value = "liu2"

// test2
class House {
  let lableHouseName = UILabel()

  init() {

  }

  var people: PeopleModel? {
    didSet {
      people?.firstName.observe{
        [unowned self] in
        self.lableHouseName.text = $0
      }
    }
  }
}

这样貌似容易理解了,O(∩_∩)O哈哈~

总结

加载全部内容

相关教程
猜你喜欢
用户评论