常用的登录界面采用ReactiveCocoa的示例

代码如下:

// 创建验证用户名的信道
    RACSignal *validUsernameSignal = [self.usernameTextField.rac_textSignal
        map:^id(NSString *text) {
            return @([self isValidUsername:text]);
        }]; 

    // 创建验证密码的信号
    RACSignal *validPasswordSignal = [self.passwordTextField.rac_textSignal 
        map:^id(NSString *text) { 
            return @([self isValidPassword:text]);
        }];


    // 通过信道返回的值,设置文本框的文字色
    RAC(self.usernameTextField, textColor) = [validUsernameSignal
        map:^id(NSNumber *usernameValid) {
            return [usernameValid boolValue] ? [UIColor colorFromHexCode:@"666666"]:[UIColor redColor];
    }];


    // 通过信道返回的值,设置文本框的文字色
    RAC(self.passwordTextField, textColor) = [validPasswordSignal
        map:^id(NSNumber *passwordValid) {
            return [passwordValid boolValue] ? [UIColor colorFromHexCode:@"666666"]:[UIColor redColor];
        }];


    // 创建登录按扭的信号,把用户名与密码合成一个信道
    RACSignal *loginActiveSignal = [RACSignal 
        combineLatest:@[
            validUsernameSignal, 
            validPasswordSignal
        ]
        reduce:^id(NSNumber*usernameValid, NSNumber *passwordValid) {
            return @([usernameValid boolValue] && [passwordValid boolValue]);
        }];


    // 订阅 loginActiveSignal, 使按扭是否可用
    [loginActiveSignal subscribeNext:^(NSNumber*loginActiveSignal) {

        if ([loginActiveSignal boolValue]) {

            self.loginButton.enabled = YES;
            [self.loginButton setBackgroundColor:[UIColor colorFromHexCode:@"1cbf61"]];
        }
        else {
            self.loginButton.enabled = NO;
            [self.loginButton setBackgroundColor:[UIColor grayColor]];
        }
    }];

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s