Swift版本 ReactiveCocoa5.0.3 基本用法
一.UI绑定 <~ 符号用法
1.某个值动态绑定到UITextField控件上来
var firstName: MutableProperty<String?> =MutableProperty<String?> (nil)
self.myTextField.reactive.text <~ firstName.producer
firstName.value = "I am Lewis"
2.输入框输入完成后赋值给firstName
var firstName: MutableProperty<String?> = MutableProperty<String?> (nil)
firstName <~ self.myTextField.reactive.textValues
二.主要用法
1.信号的创建
// 1.通过信号发生器创建(冷信号)
let producer =SignalProducer<String,NoError>.init{ (observer,_) in
print("新的订阅,启动操作")
observer.send(value:"Hello")
observer.send(value:"World")
}
let subscriber1 =Observer<String,NoError>(value: {print("观察者1接收到值\($0)") })
let subscriber2 =Observer<String,NoError>(value: {print("观察者2接收到值\($0)") })
print("观察者1订阅信号发生器")
producer.start(subscriber1)
print("观察者2订阅信号发生器")
producer.start(subscriber2)
//注意:发生器将再次启动工作
// 2.通过管道创建(热信号)
let(signalA, observerA) =Signal<String,NoError>.pipe()
let(signalB, observerB) =Signal<String,NoError>.pipe()
Signal.combineLatest(signalA, signalB).observeValues { (value) in
print("收到的值\(value.0)+\(value.1)")
}
observerA.send(value:"1")
observerA.sendCompleted()
observerB.send(value:"2")
observerB.sendCompleted()
2.文本输入框的监听
// 输入时监听
userNameTF.reactive.continuousTextValues.observeValues { text in
print(text ?? "")
}
// 监听粘贴进来的文本
let result = userNameTF.reactive.values(forKeyPath:"text")result.start { (text) in
print(text)
}
3.按钮监听
testBtn.reactive.trigger(for: .touchUpInside).observeValues{
print("按钮点击")
}
4.信号合并
// 通过管道创建
let(signalA, observerA) = Signal<String,NoError>.pipe()
let(signalB, observerB) =Signal<String,NoError>.pipe()
//第一种用法combineLatest
Signal.combineLatest(signalA, signalB).observeValues { (value) in
print("收到的值\(value.0)+\(value.1)")
}
//第二种用法zip
Signal.zip(signalA, signalB).observeValues { (value) in
print("收到的值\(value.0)+\(value.1)")
}
//第三种用法zip
signalA.zip(with: signalB).observeValues { (value) in
print("收到的值\(value.0)+\(value.1)")
}
observerA.send(value:"1")
observerA.sendCompleted()
observerB.send(value:"2")
observerB.sendCompleted()
5.调度器
// 主线程上延时0.3秒调用
QueueScheduler.main.schedule(after: Date.init(timeIntervalSinceNow:0.3)) {
print("主线程调用")
}
// 子线程上延时0.3秒调用
QueueScheduler.init().schedule(after: Date.init(timeIntervalSinceNow:0.3)){
print("子线程调用")
}
6.通知
// 普通的通知方法
var signal: Disposable? //记得在页面消失时的方法deinit里面加上这句代码signal?.dispose()来释放注册的通知
signal = NotificationCenter.default.reactive.notifications(forName: Notification.Name(rawValue:"home")).observeValues { (value) in
print(value.object??"")
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue:"home"),object: nil)
// 键盘的通知
NotificationCenter.default.reactive.notifications(forName: Notification.Name(rawValue:"UIKeyboardWillShowNotification"),object: nil).observeValues{ (value) in
print("键盘弹起")
}
NotificationCenter.default.reactive.notifications(forName: Notification.Name(rawValue:"UIKeyboardWillHideNotification"),object: nil).observeValues{ (value) in
print("键盘收起")
}