RxSwift 的使用 swift
声明
private let disposeBag = DisposeBag()
释放,需要重新设置,将上面的设置为var
disposeBag = DisposeBag()
防止cell重用时,多次订阅
//每次重用cell的时候都会释放之前的disposeBag,为cell创建一个新的dispose。保证cell被重用的时候不会被多次订阅,造成错误 override func prepareForReuse() { super.prepareForReuse() disposeBag = DisposeBag() }
1.按钮addTarget
button.rx.tap.subscribe(onNext: { [unowned self] in }).disposed(by: disposeBag)
2.View加tap事件
//Rx用法 let tapBackground = UITapGestureRecognizer() tapBackground.rx.event .subscribe(onNext: { [weak self] _ in print("Tap Tapped") }) .disposed(by: disposeBag) view.addGestureRecognizer(tapBackground)
3.KVO监听对象的某个属性
self.textFiled.rx.text.orEmpty .subscribe(onNext: { (text) in print(text) }) .disposed(by: disposeBag)
4.通知传值
NotificationCenter.default.rx .notification(UIApplication.willEnterForegroundNotification) .subscribe(onNext: { (notification) in print("Application Will Enter Foreground") }) .disposed(by: disposeBag)
6.监听视图Frame更新UI
rx.observeWeakly 可以处理属性变为空的情况,所有可以用在使用 weak 修饰的属性上。避免循环引用。
view .rx.observeWeakly(CGRect.self, "frame") .subscribe(onNext: { frame in ... })
在北京的灯中,有一盏是我家的。这个梦何时可以实现?哪怕微微亮。北京就像魔鬼训练营,有能力的留,没能力的走……
分类:
swift
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性