問題描述
在 iPad 上...
On the iPad...
textField.keyboardType = UIKeyboardTypeDecimalPad;
...只顯示常規鍵盤,但從頂部的數字開始(下面有很多標點符號).
...just shows the regular keyboard, but starting on the numbers at the top (with lots of punctuation underneath).
但它是輸入一個數字.我只希望用戶能夠鍵入數字和小數點,就像 iPhone 上的 UIKeyboardTypeDecimalPad 一樣.
But it's to type in a number. I only want the users to be able to type numbers and a decimal point, like UIKeyboardTypeDecimalPad does on the iPhone.
有什么方法可以讓不相關的鍵消失并讓我的用戶獨自一人?
Is there any way to make the irrelevant keys go away and leave my user alone?
推薦答案
設置 UITextField
的 keyboardType
只會讓用戶更容易輸入適當的字符.即使在 iPhone 上,用戶也可以通過硬件鍵盤或粘貼字符串來輸入其他字符.
Setting a UITextField
's keyboardType
only makes it easier for a user to enter appropriate characters. Even on the iPhone, users can enter other characters via a hardware keyboard, or by pasting in a string.
改為實現 UITextFieldDelegate
的 -textField:shouldChangeCharactersInRange:replacementString:
來驗證用戶輸入.您也可能真的不想硬編碼數字 0-9 和句點.例如,某些語言環境中的用戶使用逗號將整數與小數分開:
Instead, implement UITextFieldDelegate
's -textField:shouldChangeCharactersInRange:replacementString:
to validate user input. You also probably don't really want to hardcode the digits 0-9 and a period. Users in some locales, for example, separate whole numbers from decimals with a comma:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *candidate = [[textField text] stringByReplacingCharactersInRange:range withString:string];
if (!candidate || [candidate length] < 1 || [candidate isEqualToString:@""])
{
return YES;
}
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:candidate];
if (!number || [number isEqualToNumber:[NSDecimalNumber notANumber]])
{
return NO;
}
return YES;
}
或者,您可以在用戶完成輸入文本時執行驗證,在 –textFieldShouldReturn:
、–textFieldShouldEndEditing:
或 –textFieldDidEndEditing:
中根據需要.
Alternately, you might perform validation when the user finishes entering text, in –textFieldShouldReturn:
, – textFieldShouldEndEditing:
, or – textFieldDidEndEditing:
as desired.
這篇關于UITextField - iPad 上的 UIKeyboardTypeDecimalPad?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!