需要实现
UITextFieldDelegate的三个方法就行。
1.将输入框的代理设置为self;
在lb文件中将输入框的delegate设置为File’s Owner 。或者使用代码textField.delegate = self;
2.输入框对应的ViewController.h实现UITextFieldDelegate协议,并在ViewController.m中实现以下三个方法:
// 开始编辑输入框时,键盘出现,视图的Y坐标向上移动offset个单位,腾出空间显示键盘
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect textFrame = textField.frame;
int offset = textFrame.origin.y + 32 - (self.view.frame.size.height - 216.0); // 键盘高度216
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
// 将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
if (offset > 0) {
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
}
[UIView commitAnimations];
}
// 用户按下return键或者回车键,键盘消失
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
// 用户输入时
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect textFrame = textField.frame;
int offset = textFrame.origin.y + 32 - (self.view.frame.size.height - 216.0); // 键盘高度216
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
// 将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
if (offset > 0) {
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
}
[UIView commitAnimations];
}
// 用户按下return键或者回车键,键盘消失
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
// 用户输入时
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
// 输入结束后,将视图恢复到原始状态
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
return YES;
}