RAC限制UITextFeild字数,格式化输入的手机号码(3-4-4)

前提:要求输入框只能输入手机号码,手机号码的格式(3-4-4),同时控制获取验证码事件是否能交互。

使用Cocoapods来添加依赖

此处省略如何使用Cocoapods来管理

pod 'ReactiveCocoa'

如何使用


   RACSignal *phoneSignal  = self.phoneText.rac_textSignal;
    
    [phoneSignal subscribeNext:^(id x) {
        NSString *phoneString = [self phoneFormatter:x];
        
        if (phoneLogin.length >=14) {
            self.phoneText.text = [phoneLogin substringToIndex:13];
        }else
        {
            self.phoneText.text = phoneLogin;
        }
        
    }];

//格式化手机号码
- (NSString*)phoneFormatter:(NSString *)phone{
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    phone = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
    // 如果是电话号码格式化,需要添加这三行代码
    NSMutableString *temString = [NSMutableString stringWithString:phone];
    [temString insertString:@" " atIndex:0];
    phone = temString;
    NSString *newString = @"";
    while (newString.length > 0) {
        NSString *subString = [phone substringToIndex:MIN(phone.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4) {
            newString = [newString stringByAppendingString:@" "];
        }
        newString = [newString substringFromIndex:MIN(phone.length, 4)];
    }
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    return newString;
}

*根据输入框来控制 Button交互


    RAC(self.sureButton,enabled) = [RACSignal combineLatest:@[phoneSignal,self.codeText.rac_textSignal] reduce:^(NSString *phoneString,NSString *codeString){
        
        phoneString = [phoneString stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        return @(phoneString.length ==11 && codeString.length >0);
    }];
  [RACObserve(self.sureButton, enabled) subscribeNext:^(NSNumber *loggedIn) {
        if (loggedIn.boolValue) {
            self.sureButton.backgroundColor = [UIColor colorWithHexInt:0xf48400];
        }else
        {
            self.sureButton.backgroundColor = [UIColor colorWithHexInt:0xcccccc];
        }
    }];

你可能感兴趣的:(RAC限制UITextFeild字数,格式化输入的手机号码(3-4-4))