2013-11-04 55 views
0

我試圖從鍵盤輸入每個字符時添加空格,但問題是我無法刪除,複製或編輯文本。在UITextField中的字符後面添加空格

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

} 
+0

我對'UITextField's沒有專家,但是你直接更改UI控件和不使用提供的委託方法。你可能會混淆控制。 – trojanfoe

+0

問題的症狀是什麼?代碼是否崩潰,代碼執行時什麼都不會發生?代碼是否執行? – nio

+0

我可以添加10 charctere像1 8 9 0 ...但是當我想要刪除charctare沒有任何反應,這意味着它確定代碼不會崩潰,但我鬆開控制刪除任何charctere – mobileHard

回答

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; 
} 
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; 
} 
+0

這看起來也是錯誤的。爲什麼控制支持控制文本應該包含的代表並且還支持直接改變文本?我看不到這個工作。 – trojanfoe

+0

完美,thx我broooo – mobileHard

+0

它的工作非常好 – mobileHard

相關問題