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
            ...
          })

 

posted @ 2022-06-28 16:24  黄增松  阅读(348)  评论(0编辑  收藏  举报