在TextField中的字符后添加空格

时间:2015-07-22 12:23:08

标签: ios xcode6 uitextfield

我正在创建SDK,其中用户需要输入4位数的PIN,每个字符后应该有空格,文本字段应该是secureTextEntry启用。我正在编写以下代码

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

   NSUInteger newLength = [textField.text length] + [string length] - range.length;

    NSString *text = [textField.text stringByReplacingCharactersInRange:range
                                                             withString: string];


     if (text.length < 13)
    {
        textField.text = [NSString stringWithFormat: @"%@  ", text];

        return NO;
    }

    return newLength <= 12;


}

但问题是我在字符空间之间添加空格也显示为点。此解决方案在非SDK代码中工作正常。我正在努力寻找任何简单的解决方案

提前致谢

1 个答案:

答案 0 :(得分:0)

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

         NSUInteger length = [textField.text length] + [string length] - range.length;

      if (length < 10) {

    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSString *lastString = [NSString stringWithFormat:@"%c",[newString characterAtIndex:newString.length-1]];

   if(![lastString isEqualToString:@" "] && ![string isEqualToString:@""])
       newString = [newString stringByAppendingString:@" "];
   else {

       NSRange tempR = NSMakeRange(range.location-1, 2);

       newString = [textField.text stringByReplacingCharactersInRange:tempR withString:@""];
   }

   textField.text = newString;
  }

return NO;

}