美文网首页
RxSwift学习(2)

RxSwift学习(2)

作者: 忆痕无殇 | 来源:发表于2019-07-23 20:03 被阅读0次

接1
准备工作都做好了之后就开始试着写一写了。来感受下
首先:要引入

 import RxSwift
 import RxCocoa

1:网络请求

 //网络请求
    func setupNextwork() {
        let url = URL(string: "https://www.baidu.xom")
        URLSession.shared.rx.response(request: URLRequest(url: url!))
            .subscribe(onNext : { (response,data) in
                print(response)
            }).disposed(by: disposeBag)//回收机制
    }
    public var rx: RxSwift.Reactive<Self>

2:定时器

  func setupTimer() {
        timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
        timer.subscribe(onNext : { (num) in
            print(num)
        })
        .disposed(by: disposeBag)
    }

在这里报了个警告:'interval(_:scheduler:)' is deprecated: Use DispatchTimeInterval overload instead. 告诉有更好的替代方法。用的时候注意。
核心实现是通过一个Observable监听响应。

3:通知

 //通知
    func setupNotification() {
        NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification)
            .subscribe(onNext :{(noti) in
                print(noti)
            })
        .disposed(by: disposeBag)
    }

4:手势

 //手势
    func setupGestureRecognizer()  {
        let tap = UITapGestureRecognizer()
        self.view.addGestureRecognizer(tap)
        self.view.isUserInteractionEnabled = true
        tap.rx.event.subscribe(onNext : { (tap) in
            print(tap.view as Any)
        })
        .disposed(by: disposeBag)
    }
    /*
     warning:Expression implicitly coerced from 'UIView?' to 'Any'
     */
    /*
     explain:This will happen when the function you are calling has a parameter of type Any, and you are passing an optional
     */
    /*
     slove:In order to avoid the warning you have to either force unwrap your optional, or cast it to Any.
     */

5:scrollerView

 func setupScrollerView() {
        scrollerView.rx.contentOffset
            .subscribe(onNext :{ [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)
    }

注意:scroller设置contentSize才能进行滚动。

6:KVO的使用
注册观察

  func setupKVO()  {
        self.addObserver(self, forKeyPath: "name", options: .new, context: nil)
    }

改变

   override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textFiled.resignFirstResponder()
        print("来了")
        person.name = "\(person.name) +"
        // print(person.name)
    }

销毁

  override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print("响应")
        print(change as Any)
    }

销毁

    deinit {
        self.removeObserver(self.person, forKeyPath: "name", context: nil)
    }

注意:swift是静态语言,要使用KVO动态观察需要添加 @objc dynamic 使用OC语法访问开启运行时模式。

相关文章

网友评论

      本文标题:RxSwift学习(2)

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