以下主要是swift的一些基本交互,对比OC,Swift,RXSwift的写法,感受RX的牛逼之处。。。
所有的控件的UI创建和布局不做展示,自己敲0.0
刚刚接触swift,如有不对,各位请不吝赐教。
首先定义 let disposeBag = DisposeBag() 这是一个RXSwift的内存回收
1.基本的网络请求
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定时器
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是一种自己定义的状态,进行不断的改变达到类似于OC的timer的效果,所以rx的timer不受runloop的影响。
var timer:Observable!
timer = Observable<Int>.interval(5, scheduler: MainScheduler.instance)//放在主线程执行 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.手势
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被点击了")
}
}
RXSwift中的写法:
let tap = UITapGestureRecognizer()
self.label.addGestureRecognizer(tap)
self.label.isUserInteractionEnabled = true
tap.rx.event
.subscribe(onNext: { (tap) in
print("label被点击了")
})
.disposed(by: disposeBag)
5.scrollView的滑动事件响应
这个就写了一个RXSwift的写法,其他的费事没去实现:
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
//然后去实现代理
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响应
OC中的写法:
//这个我不会~~~
Swift的写法:
self.button.addTarget(self, action: #selector(self.buttonClick(btnclick:)), for: .touchUpInside)
@objc func buttonClick(btnclick:UIButton){
print("bbuttonb被点击了~~~~")
}
RXSwift中的写法:
self.button.rx.tap
.subscribe(onNext: { () in
print("bbuttonb被点击了~~~~")
})
.disposed(by: disposeBag)
8.KVO
这里首先需要创建一个Person类,定义一个监听的属性name,下面直接给出swift的Person创建
import UIKit
class LGPerson: NSObject {
//@objc 用OC调用这段代码 dynamic(动态的)--> 启用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)
最后给出一个点击空白处的touch事件响应方法
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 += "+呵呵哒";
}
网友评论