Swift 以前是通过addObserver
来实现对某个属性的变化监听,而最新的变化,书写起开更加方便。
1
2
3
|
observer = test.observe(\.field, options: [. new , .initial]) { (object, change) in
print(change)
}
|
一定要用属性赋值当前的 observe 结果,没有的话可能会造成 change 不生效。
对 UIScrollView 的滚动监听,我们可以使用UIScrollViewDelegate
1
2
3
4
5
|
extension UIScrollViewDelegate{
func scrollViewDidScroll(scrollView: UIScrollView){
//do something
}
}
|
这里推荐使用 Observe 比较方便的是可以进行模块的逻辑的拆分,我们只需在自己的组件里面进行监听
1
2
3
4
5
6
7
8
|
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属性监控机制。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
//: 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哈哈~
总结
到此这篇关于Swift 使用 Observe 监测页面滚动的文章就介绍到这了,更多相关Swift 使用 Observe 监测页面滚动内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.jackpu.com/swift-shi-yong-observe-jian-ce-ye-mian-gun-dong/