0

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

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

}
4

2 回答 2

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;
}
于 2013-11-04T12:00:23.523 回答
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; 
}
于 2013-11-04T11:42:23.427 回答