實際開發中在退出當前界面前,要將彈起的鍵盤收起
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// 視圖退出編輯狀態(收起鍵盤)
[self.view endEditing:YES];
}
如果當前控制器是TableViewController時,就不能這么寫了
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// 關閉第一響應者(收起鍵盤)
[self.textField resignFirstResponder];
}
在實際開發中有時候需要對 文本輸入框UITextfiled 進行一些限制.
比如說在輸入金額的時候我們希望只能輸入最多兩位小數.應該怎么辦呢?UITextfiled 有個代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
官方的注釋是** return NO 的時候是不能改變文字的.那么我們就在這個方法里做手腳.為了少做一些判斷.我們可以先限制調出的鍵盤類型為UIKeyboardTypeDecimalPad.
// 輸入金額 限制兩個小數
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([textField.text containsString:@"."]) {
if ([string isEqualToString:@"."]) return NO;
NSRange rangeOfPoint = [textField.text rangeOfString:@"."];
if (range.location > rangeOfPoint.location + 2) return NO;
}
return YES;
}
附錄: 鍵盤樣式:
UIKeyboardTypeDefault
UIKeyboardTypeASCIICapable
UIKeyboardTypeNumbersAndPunctuation
UIKeyboardTypeURL
UIKeyboardTypeNumberPad
UIKeyboardTypePhonePad電話號碼鍵盤
UIKeyboardTypeNamePhonePad
UIKeyboardTypeEmailAddress
UIKeyboardTypeDecimalPad金額鍵盤
UIKeyboardTypeTwitter
UIKeyboardTypeWebSearch
UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable