美文网首页
RxSwift 初探1

RxSwift 初探1

作者: bill666500 | 来源:发表于2022-08-24 11:08 被阅读0次
    通过 Cocoapods 导入
    pod 'RxSwift', '6.5.0'
    pod 'RxCocoa', '6.5.0'
    
    
    使用三步曲
    • 注册监听
    • 订阅
    • 销毁

    RXSwift 实际应用

    • KVO
           
    func  setupKVO(){
    //响应序列 
    self.person.rx.observeWeakly(String.self, "name")
            .subscribe { value in
                print(value as Any)
            }
            .disposed(by: disposeBag)
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("来了")
        person.name = "\(person.name) 6"
    }
    
    
    因为使用了kvo监听的原理,所以类中的属性必须使用@objc dynamic 来修饰 ,dynamic 是开启运行时机制。
    class LGPerson: NSObject {
       @objc dynamic var name: String = "Bill"
    }
    
    
    • button
    func setupButton(){
        button.rx.controlEvent(.touchUpInside)
            .subscribe { _ in
                print("点击事件")
            }
            .disposed(by: disposeBag)
    }
    
    
    • textfiled
    func setupTextField(){
        textFiled.rx.text.orEmpty.changed
            .subscribe { text in
                print(text)
            }
            .disposed(by: disposeBag)
    }
    
    • scrollView
    func setupScrollerView() {
        scrollView.rx.contentOffset
                .subscribe { [weak self]content in
                    self?.view.backgroundColor = UIColor.init(red: content.y/255*0.8, green: content.y/255*0.6, blue: content.y/255*0.3, alpha: 1)
                }
                .disposed(by: disposeBag)
    
        }
    
    
    • 手势
    func setupGestureRecongizer(){
       let tap = UITapGestureRecognizer()
       self.view.addGestureRecognizer(tap)
       self.view.isUserInteractionEnabled = true
    
       tap.rx.event
           .subscribe { tap in
               print(tap.view)
           }
           .disposed(by: disposeBag)
       
    }
    
    
    • 通知
    func setupNotification(){
        // 监听键盘弹出通知
        NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification)
                .subscribe { noti in
                    print("键盘弹起")
                }
                .disposed(by: disposeBag)
    }
    
    
    • timer定时器
    func setupTimer(){
        var timer: Observable<Int> = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
            timer.subscribe { num in
                print(num)
            }
            .disposed(by: disposeBag)
    }
    
    
    • 网络请求
    func setupNetwork() {
        let url = URL(string: "https://www.baidu.com")
        URLSession.shared.rx.response(request: URLRequest(url: url!))
            .subscribe { response, data in
                print(response)
            }
            .disposed(by: disposeBag)
    }
    
    

    相关文章

      网友评论

          本文标题:RxSwift 初探1

          本文链接:https://www.haomeiwen.com/subject/oiwngrtx.html