美文网首页
iOS几种常用的自定义TextField

iOS几种常用的自定义TextField

作者: KimmyKing | 来源:发表于2017-12-01 16:59 被阅读0次

    BaseTextField:空格开始输入

    实现代码:

    - (void)prepareTextFieldWithDefaultSetting

    {

    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];

    self.leftView = leftView;

    self.leftViewMode = UITextFieldViewModeAlways;

    }

    编辑前 编辑时

    MoneyTextField:限制输入的文本符合规则

    实现代码:

    //MARK: - UITextFieldDelegate

    //MARK: --开始编辑时

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSString *myDotNumbers = @"0123456789.\n";

    NSString *myNumbers = @"0123456789\n";

    // 判断是否输入内容,或者用户点击的是键盘的删除按钮

    if (![string isEqualToString:@""]) {

    NSCharacterSet *characterSet;

    // 小数点在字符串中的位置 第一个数字从0位置开始

    NSInteger dotLocation = [textField.text rangeOfString:@"."].location;

    // 判断字符串中是否有小数点,并且小数点不在第一位

    // NSNotFound 表示请求操作的某个内容或者item没有发现,或者不存在

    // range.location 表示的是当前输入的内容在整个字符串中的位置,位置编号从0开始

    if (dotLocation == NSNotFound && range.location != 0) {

    // 取只包含“myDotNumbers”中包含的内容,其余内容都被去掉

    /*

    [NSCharacterSet characterSetWithCharactersInString:myDotNumbers]的作用是去掉"myDotNumbers"中包含的所有内容,只要字符串中有内容与"myDotNumbers"中的部分内容相同都会被舍去在上述方法的末尾加上invertedSet就会使作用颠倒,只取与“myDotNumbers”中内容相同的字符

    */

    characterSet = [[NSCharacterSet characterSetWithCharactersInString:myDotNumbers] invertedSet];

    if (range.location >= 9) {

    NSLog(@"单笔金额不能超过亿位");

    if ([string isEqualToString:@"."] && range.location == 9) {

    return YES;

    }

    return NO;

    }

    }else {

    characterSet = [[NSCharacterSet characterSetWithCharactersInString:myNumbers] invertedSet];

    }

    // 按characterSet分离出数组,数组按@""分离出字符串

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""];

    BOOL basicTest = [string isEqualToString:filtered];

    if (!basicTest) {

    NSLog(@"只能输入数字和小数点");

    return NO;

    }

    if (dotLocation != NSNotFound && range.location > dotLocation + 2) {

    NSLog(@"小数点后最多两位");

    return NO;

    }

    if (textField.text.length > 11) {

    return NO;

    }

    }

    return YES;

    }



    PhoneTextField:自动匹配3-4-4手机格式,并提供检测输入的手机号码是否合法的接口

    实现代码:

    //MARK: -

    //MARK: --输入框的文本改变时

    - (void)actionEditingChanged:(PhoneTextField *)textField

    {

    //当前光标位置

    NSInteger currentPosition = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];

    NSString *onlyNumberString = [self getOnlyNumberStringFromString:textField.text position:¤tPosition];

    //限制字数

    if (onlyNumberString.length > 11) {

    textField.text = _lastText;

    textField.selectedTextRange = _currentTextRange;

    return;

    }

    NSString *phoneResultString = [self getPhoneResultFromSourceString:onlyNumberString position:¤tPosition];

    textField.text = phoneResultString;

    UITextPosition *targetPosition = [textField positionFromPosition:textField.beginningOfDocument offset:currentPosition];

    UITextRange *range = [textField textRangeFromPosition:targetPosition toPosition:targetPosition];

    textField.selectedTextRange = range;

    }

    /**

    剔除非阿拉伯数字的函数

    @param sourceString 需要校验的字符串

    @param position 当前的光标位置

    @return 处理后只包含阿拉伯数字的字符串

    */

    - (NSString *)getOnlyNumberStringFromString:(NSString *)sourceString position:(NSInteger *)position

    {

    NSMutableString *mstr = [NSMutableString string];

    NSInteger tempPosition = *position;

    for (int i = 0 ; i < sourceString.length; i++) {

    unichar character = [sourceString characterAtIndex:i];

    //isdigit:检查参数c是否为阿拉伯数字0到9

    if (isdigit(character)) {

    //将unichar转为NSString

    NSString *numberString = [NSString stringWithCharacters:&character length:1];

    [mstr appendString:numberString];

    }else{

    //检测到非阿拉伯数字时,且遍历到的下标小于 当前光标位置,需要将当前光标的位置-1(计算纯阿拉伯数字的下标)

    if (i < tempPosition) {

    (*position)--;

    }

    }

    }

    return mstr.copy;

    }

    /**

    指定位置添加分隔符号

    @param soureceString 需要校验的字符串

    @param position 当前的光标位置

    @return 添加符号后的电话号码

    */

    - (NSString *)getPhoneResultFromSourceString:(NSString *)soureceString position:(NSInteger *)position

    {

    NSMutableString *mstr = [NSMutableString string];

    NSInteger tempPosition = *position;

    for (int i = 0; i < soureceString.length; i++) {

    if (i == 3 || i == 7) {

    [mstr appendString:@"-"];

    if (i < tempPosition) {

    (*position)++;

    }

    }

    unichar character = [soureceString characterAtIndex:i];

    NSString *str = [NSString stringWithCharacters:&character length:1];

    [mstr appendString:str];

    }

    return mstr.copy;

    }

    //MARK: - UITextFieldDelegate

    //MARK: --输入框开始编辑时

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

    {

    _lastText = textField.text;

    _currentTextRange = textField.selectedTextRange;

    return YES;

    }

    //MARK: -

    //MARK: --检测手机号码是否正确

    - (BOOL)isCorrectPhoneNumber

    {

    [self resignFirstResponder];

    //正则表达式(匹配手机号3-4-4格式)

    NSString *pattren = @"^1[3578]+\\d-\\d{4}-\\d{4}";

    //SELF MATCHES:匹配正则表达式

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattren];

    //评估输入的手机号是否匹配

    return [predicate evaluateWithObject:self.text];

    }

    调用方法:

    - (IBAction)checkPhoneNumber:(id)sender {

    if ([self.phoneTF isCorrectPhoneNumber]) {

    NSLog(@"This is a correct phone number");

    }else{

    NSLog(@"This is a error phone number");

    }

    }


    VecodeTextField:带计时器的验证码输入框

    实现代码:

    - (void)prepareTextFieldWithDefaultSetting

    {

    [super prepareTextFieldWithDefaultSetting];

    self.keyboardType = UIKeyboardTypeNumberPad;

    self.rightViewMode = UITextFieldViewModeAlways;

    _button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];

    _button.backgroundColor = [UIColor whiteColor];

    _button.titleLabel.font = [UIFont systemFontOfSize:12];

    _button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;

    [_button setTitle:@"获取验证码" forState:UIControlStateNormal];

    [_button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];

    [_button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];

    self.rightView = _button;

    }

    //MARK: -

    //MARK: -- 点击获取验证码按钮

    - (void)clickButton:(UIButton *)sender

    {

    sender.enabled = NO;

    _second = 60;

    if ([_vecodeDelegate respondsToSelector:@selector(clickButtonWithTextField:startTimer:reenableButton:)]) {

    [_vecodeDelegate clickButtonWithTextField:self startTimer:@selector(startTimer) reenableButton:@selector(reenableButton)];

    }

    }

    - (void)startTimer

    {

    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countdown) userInfo:nil repeats:YES];

    }

    - (void)reenableButton

    {

    [self resetTextField];

    }

    - (void)countdown

    {

    _second--;

    [self.button setTitle:[NSString stringWithFormat:@"%d",_second] forState:UIControlStateNormal];

    if (_second < 0) {

    [self resetTextField];

    }

    }

    - (void)resetTextField

    {

    [_button setTitle:@"重获验证码" forState:UIControlStateNormal];

    [_timer invalidate];

    _second = 60;

    _button.enabled = YES;

    }

    调用代理方法:

    //MARK: -

    //MARK: --VecodeTFDelegate

    - (void)clickButtonWithTextField:(VecodeTextField *)textField startTimer:(SEL)startTimer reenableButton:(SEL)reenableButton

    {

    //开始倒计时

    if ([textField respondsToSelector:startTimer]) {

    [textField performSelector:startTimer];

    }

    self.reenableButton = reenableButton;

    }

    //MARK: -

    //MARK: --停止计时器

    - (IBAction)stopTimer:(id)sender {

    if ([self.vecodeTF respondsToSelector:self.reenableButton]) {

    [self.vecodeTF performSelector:self.reenableButton];

    }

    }

    demo地址:戳我

    喜欢请给个赞哦~

    相关文章

      网友评论

          本文标题:iOS几种常用的自定义TextField

          本文链接:https://www.haomeiwen.com/subject/ibewbxtx.html