常用宏
#import <ReactiveObjC/ReactiveObjC.h>
@weakify(self)
@strongify(self)
单向绑定与双向绑定
// 单向绑定
RAC(self, vcProperty) = RACObserve(self.viewModel, vmProperty);
// 双向绑定
RACChannelTo(self.textField, text) = RACChannelTo(self.viewModel, someProperty)
有什么区别?
属性观察
[[RACObserve(self.webView, estimatedProgress) takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNumber * _Nullable estimatedProgress) {
NSLog(@"jeffery estimatedProgress: %@",estimatedProgress);
}];
[self.button rac_liftSelector:@selector(setTitle:forState:) withSignals:RACObserve(data, nameErrorText), [RACSignal return:@(UIControlStateNormal)], nil];
监听通知
// 打破循环引用
// 通知自释放
@weakify(self)
[[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] takeUntil:[self rac_willDeallocSignal]] subscribeNext:^(NSNotification * _Nullable sender) {
@strongify(self)
}];
Cell 复用
[[RACObserve(data, addressText) takeUntil:self.rac_prepareForReuseSignal] subscribeNext:^(NSString* _Nullable addressText) {
@strongify(self)
self.addressContentTextField.text = addressText;
}];
[[self.addressContentTextField.rac_textSignal takeUntil:self.rac_prepareForReuseSignal] subscribeNext:^(NSString * _Nullable text) {
data.addressText = text;
}];
UITextField 双向绑定
RACChannelTo(data, cardName) = RACChannelTo(self.nameTextField, text);
[[self.nameTextField.rac_textSignal takeUntil:self.rac_prepareForReuseSignal] subscribe:RACChannelTo(data, cardName)];
银行卡格式
[[[self.cardNumTextField rac_signalForControlEvents:UIControlEventEditingChanged] takeUntil:self.rac_prepareForReuseSignal] subscribeNext:^(UITextField * _Nullable textField) {
NSString *text = [[textField text] stringByReplacingOccurrencesOfString:@" " withString:@""];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
NSString *newString = @"";
while (text.length > 0) {
NSString *subString = [text substringToIndex:MIN(text.length, 4)];
newString = [newString stringByAppendingString:subString];
if (subString.length == 4) {
newString = [newString stringByAppendingString:@" "];
}
text = [text substringFromIndex:MIN(text.length, 4)];
}
newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
if ([newString stringByReplacingOccurrencesOfString:@" " withString:@""].length < 21) {
[textField setText:newString];
data.cardNumber = [newString stringByReplacingOccurrencesOfString:@" " withString:@""];
}
}];