在项目中常见的使用功能
1.下面样例中我们将 textField 里输入的内容实时地显示到控制台中。时时监听输入的内容 (比较常见功能)(同时监听多个 textField 内容的变化不列举)
//当文本框内容改变时,将内容输出到控制台上
textField.rx.text.orEmpty.asObservable()
.subscribe(onNext: {
print("您输入的是:\($0)")
})
.disposed(by:disposeBag)
2.监听输入框的输入内容数量
//当文本框内容改变
letinput = textField.rx.text.orEmpty.asDriver()// 将普通序列转换为 Driver
.throttle(0.3) //在主线程中操作,0.3秒内值若多次改变,取最后一次
//内容绑定到文本标签中 map中的数据类型需要跟drive中填充的类型一致
input.map{"当前字数:\($0.count)"}
.drive(label.rx.text)
.disposed(by:disposeBag)
//根据内容字数决定按钮是否可用
input.map{ $0.count>5}
.drive(button.rx.isEnabled)
.disposed(by:disposeBag)
3.button使用 swift\UISegmentedControl\slider\也是类似
//将按钮的响应事件放入到自己的懒加载中 起到代码解耦的作用 也更加直观
lazyvarbutton:UIButton= {
letbutton =UIButton(type: .custom)
button.setTitle("测试按钮方法", for: .normal)
button.titleLabel?.font=UIFont.systemFont(ofSize:18)
button.backgroundColor = UIColor.yellow
button.setTitleColor(UIColor.white, for:.normal)
//按钮点击响应
button.rx.tap.bind{ [weakself]in
self?.showMessage("按钮被点击")
}.disposed(by:disposeBag)
returnbutton
}()
4.双向绑定将model中的数据跟UI界面展示进行绑定,适用于点赞\评论等时时变化的数据进行UI刷新跟数据同步
userVM.username.asObservable().bind(to:textField.rx.text).disposed(by:disposeBag)textField.rx.text.orEmpty.bind(to:userVM.username).disposed(by:disposeBag)
5.通知的用法
//发送通知letnotificationName=Notification.Name(rawValue:"DownloadImageNotification")NotificationCenter.default.post(name:notificationName,object:self,userInfo:["value1":"hangge.com","value2":12345])
//接收通知letnotificationName=Notification.Name(rawValue:"DownloadImageNotification")_=NotificationCenter.default.rx.notification(notificationName).takeUntil(self.rx.deallocated)//页面销毁自动移除通知监听.subscribe(onNext:{notificationin//获取通知数据letuserInfo=notification.userInfoas![String:AnyObject]letvalue1=userInfo["value1"]as!Stringletvalue2=userInfo["value2"]as!Intprint("\(name)获取到通知,用户数据是[\(value1),\(value2)]")//等待3秒sleep(3)print("\(name)执行完毕")})
这个用法的好处就是当页面注销掉之后通知会跟随回收,防止内存泄漏