RXSwift的一些基本交互(OC,Swift,RXSwift對(duì)比)

以下主要是swift的一些基本交互,對(duì)比OC,Swift,RXSwift的寫法,感受RX的牛逼之處。。。
所有的控件的UI創(chuàng)建和布局不做展示,自己敲0.0
剛剛接觸swift,如有不對(duì),各位請(qǐng)不吝賜教。
首先定義 let disposeBag = DisposeBag() 這是一個(gè)RXSwift的內(nèi)存回收

1.基本的網(wǎng)絡(luò)請(qǐng)求
OC中的寫法:

  NSURLRequest*request = [NSURLRequestrequestWithURL:[NSURL URLWithString:"https://www.baidu.com"]];
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSArray *array = [rootDic objectForKey:@"applications"];
            for(NSDictionary *dicinarray) {
            NSLog(@"%@",[dic objectForKey:@"name"]);
            }
        }];

Swift的寫法:

 let url = URL(string: "https://www.baidu.com")
        URLSession.shared.dataTask(with: url!) { (data, response, error)in
            print(String.init(data: data!, encoding: .utf8)asAny)
        }.resume()

RXSwift中的寫法:

  let url = URL(string: "https://www.baidu.com")
        URLSession.shared.rx.response(request: URLRequest(url: url!))
            .subscribe(onNext: { (response,data)in
                print(response)
            })
            .disposed(by:disposeBag)

2.timer定時(shí)器
OC中的寫法:

NSTimer *timer  = [NSTimer scheduledTimerWithTimeInterval:60.0target:selfselector:@selector(timerAction) userInfo:nilrepeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

Swift的寫法:

   Timer.scheduledTimer(timeInterval:5, target:self, selector:#selector(timeSelect), userInfo:nil, repeats:true)
        @objcfunctimeSelect() {
                print("----")
            }

RXSwift中的寫法:
RX中的timer和OC不一樣,rx中的timer是一種自己定義的狀態(tài),進(jìn)行不斷的改變達(dá)到類似于OC的timer的效果,所以rx的timer不受runloop的影響。

var timer:Observable!
timer = Observable<Int>.interval(5, scheduler: MainScheduler.instance)//放在主線程執(zhí)行 MainScheduler.instance
        timer.subscribe(onNext: { (num)in
            print(num)
        })
        .disposed(by:disposeBag)

3.通知
OC中的寫法:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeScrollStatus:) name:@"leaveTop" object:nil];

- (void)changeScrollStatus:(NSNotification *)notification{
        NSDictionary *dic = notification.object;
    }
    -(void)dealloc{
         [[NSNotificationCenter defaultCenter] removeObserver:self name:@"leaveTop" object:nil];
    }

Swift的寫法:

NotificationCenter.default.addObserver(self, selector: #selector(testNotifi), name: NSNotification.Name(rawValue: "testNotifi"), object: nil)

@objc func testNotifi(nofi:Notification){
        let str = nofi.userInfo!["post"]
        print(String(describing: str!) + " this notifi")
    }

RXSwift中的寫法:

 NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification)
            .subscribe(onNext: { (noti) in
                print("接收到鍵盤彈出\(noti)")
            })
            .disposed(by: disposeBag)

4.手勢(shì)
OC中的寫法:

UITapGestureRecognizer *tapgesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapgestureClick:)];
        [self.view addGestureRecognizer:tapgesture];

Swift的寫法:

 self.label.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.titlelabelClick(tapGes:)))
        self.label.addGestureRecognizer(tap)


@objc func titlelabelClick(tapGes:UITapGestureRecognizer){
        if tapGes.state == .ended{
            print("label被點(diǎn)擊了")
        }
        
    }

RXSwift中的寫法:

let tap = UITapGestureRecognizer()
        self.label.addGestureRecognizer(tap)
        self.label.isUserInteractionEnabled = true
        tap.rx.event
            .subscribe(onNext: { (tap) in
                print("label被點(diǎn)擊了")
            })
        .disposed(by: disposeBag)

5.scrollView的滑動(dòng)事件響應(yīng)
這個(gè)就寫了一個(gè)RXSwift的寫法,其他的費(fèi)事沒去實(shí)現(xiàn):

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

6.textfiled的輸入
OC中的寫法:

textFiled.delegate  = self

//然后去實(shí)現(xiàn)代理

Swift的寫法:

textFiled.delegate  = self

extension ViewController: UITextFieldDelegate{
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        print("textfield----\(string)" )
        return true
    }
    
}

RXSwift中的寫法:

 self.textFiled.rx.text.orEmpty
            .subscribe(onNext: { (text) in
                print(text)
            })
            .disposed(by: disposeBag)

7.button響應(yīng)
OC中的寫法:

//這個(gè)我不會(huì)~~~

Swift的寫法:

self.button.addTarget(self, action: #selector(self.buttonClick(btnclick:)), for: .touchUpInside)

@objc func buttonClick(btnclick:UIButton){
         print("bbuttonb被點(diǎn)擊了~~~~")
    }
    

RXSwift中的寫法:

self.button.rx.tap
            .subscribe(onNext: { () in
                print("bbuttonb被點(diǎn)擊了~~~~")
            })
            .disposed(by: disposeBag)

8.KVO

這里首先需要?jiǎng)?chuàng)建一個(gè)Person類,定義一個(gè)監(jiān)聽的屬性name,下面直接給出swift的Person創(chuàng)建

import UIKit

class LGPerson: NSObject {
   //@objc  用OC調(diào)用這段代碼    dynamic(動(dòng)態(tài)的)--> 啟用OC 的runtime
   @objc dynamic var name:String = "小莊"
}

OC中的寫法:

[self.person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];

    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
        NSLog(@"%@",change[NSKeyValueChangeNewKey]);
    }
    -(void)dealloc{
        [self.person removeObserver:self forKeyPath:"name"];
    }

Swift的寫法:

self.person.addObserver(self, forKeyPath: "name", options: .new, context: nil)

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print(change?[.newKey] as? String ?? "完了,沒拿到值")
    }

RXSwift中的寫法:

  self.person.rx.observeWeakly(String.self, "name")
            .subscribe(onNext: { (value) in
                print("rx KVO == \(value!)")
            })
        .disposed(by: disposeBag)

最后給出一個(gè)點(diǎn)擊空白處的touch事件響應(yīng)方法

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touch")
        NotificationCenter.default.post(name: NSNotification.Name("testNotifi"), object: self, userInfo: ["post":"通知接收的消息到了"])
        self.view.endEditing(false)
        self.person.name += "+呵呵噠";
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容