在UITextField中添加字符后的空格

时间:2013-11-04 11:12:53

标签: ios objective-c

当我从键盘输入每个字符时,我试图添加空格,但问题是我无法删除,复制或编辑文本。

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

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

    if ([textField tag] == textTag && newLength <= 10) {
        textField.text = [textField.text stringByAppendingString:@" "];
        length ++;
        NSLog(@"%d", length);
    } else {
        NSLog(@"%d", length);
        return NO;
    }

    return YES;

}

2 个答案:

答案 0 :(得分:1)

你也可以这样做..

- (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;
}

答案 1 :(得分:0)

试试这个:

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSUInteger length = [textField.text length] + [string length] - range.length;

    if (length < 10) {
        textField.text = [textField.text stringByAppendingString:@" "];
        length++;

        NSLog(@"%d", length);
    }
    else if (length >= 10 && string.length > 0)
    {
        NSLog(@"%d", length);
        return NO;
    }  

    if (string.length == 0) {
        textField.text = [textField.text substringWithRange:NSMakeRange(0, length - 1)];
        return YES;
    }

    return YES; 
}