2010-01-15 79 views
5

我在表格上輸入UITextFields來輸入值。 其中一些字段只接受數字。我使用鍵盤類型UIKeyboardTypeNumbersAndPunctuationshouldChangeCharactersInRange來過濾字符。如何在觸摸空格鍵時防止鍵盤從數字改爲字母?

此外,所有的修正將被禁用:

textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation; 
textField.autocorrectionType = UITextAutocorrectionTypeNo; 
textField.autocapitalizationType = UITextAutocapitalizationTypeNone; 

上的數字僅領域,當空格鍵被觸摸,鍵盤變爲字母。 我知道這是默認行爲。 我想忽略空格鍵,不想更改鍵盤類型。

有什麼方法可以改變這種默認行爲嗎?

PS:其他數字鍵盤類型不是一個選項。我需要標點符號!

謝謝

回答

4

我不認爲有可能修改鍵盤的行爲。

但是,你可以實現從UITextFieldDelegate協議攔截的空間(和撇號)這樣的textField:shouldChangeCharactersInRange:replacementString:,它似乎工作:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    if ([string isEqualToString:@" "] || [string isEqualToString:@"'"]) { 
     NSMutableString *updatedString = [NSMutableString stringWithString:textField.text]; 
     [updatedString insertString:string atIndex:range.location]; 
     textField.text = updatedString; 
     return NO; 
    } else { 
     return YES; 
    } 
}