关键步骤
- 引入ReactiveCocoa框架。
- 对
UITextField
的文本变化事件进行绑定。
- 在绑定的闭包中进行实时校验。
- 将校验结果绑定到按钮的
enabled
属性上。
代码示例
#import <ReactiveCocoa/ReactiveCocoa.h>
@interface ViewController ()
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIButton *button;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 200, 40)];
[self.view addSubview:self.textField];
self.button = [UIButton buttonWithType:UIButtonTypeSystem];
self.button.frame = CGRectMake(100, 200, 200, 40);
[self.button setTitle:@"按钮" forState:UIControlStateNormal];
[self.view addSubview:self.button];
@weakify(self);
RACSignal *textSignal = [self.textField.rac_textSignal map:^id(NSString *text) {
@strongify(self);
// 这里进行校验,例如判断文本长度是否大于0
return @(text.length > 0);
}];
RAC(self.button, enabled) = textSignal;
}
@end