ReactiveSwift示例

1、UIButton监听点击

1
2
3
btn.reactive.controlEvents(.touchUpInside).observeValues { (btn) in
print("点到我了")
}

2、UItextfield监听

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 监听tf的输入值
tf.reactive.continuousTextValues.observeValues { (text) in
print(text ?? "")
}
// 监听tf的输入长度
tf.reactive.continuousTextValues.map { (text) -> Int in
return text!.characters.count
}.observeValues { (count) in
print(count)
}
// 当输入字符长度大于3时,才会接收到信息
tf.reactive.continuousTextValues.filter { (text) -> Bool in
return text!.characters.count>3
}.observeValues { (text) in
print(text ?? "")
}

3、监听UIViewController的viewWillAppear方法

1
2
3
self.reactive.trigger(for: #selector(UIViewController.viewWillAppear(_:))).observeValues { () in
print("viewWillAppear被调用了哦")
}

4、在OneVC里,监听TwoVC的deinit

1
2
3
4
5
let twoVC = TwoVC()
twoVC.reactive.lifetime.ended.observeCompleted {
print("textVC已成功销毁")
}
navigationController?.pushViewController(twoVC, animated: true)

5、RAC替换代理

1
2
3
4
// 监听_redView有没有调用btnClick:,如果调用了就会转换成信号
[[_redView rac_signalForSelector:@selector(btnClick:)] subscribeNext:^(id x) {
NSLog(@"控制器知道,点击了红色的view");
}];

6、KVO

1
2
3
4
5
6
7
8
9
@property (nonatomic, assign) int age;
// 把监听到内容转换成信号
[[self rac_valuesForKeyPath:@"age" observer:nil] subscribeNext:^(id x) {
// block:只要属性改变就会调用,并且把改变的值传递给你
NSLog(@"%@",x);
}];
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.age++;
}

7、监听通知

1
2
3
4
// 只要发出这个通知,又会转换成一个信号
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] subscribeNext:^(id x) {
NSLog(@"弹出键盘");
}];

打赏支持一下呗!