实际开发中在退出当前界面前,要将弹起的键盘收起
- (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