1)首先得遵守协议UITextFieldDelegate
@interface userInfoViewController()<UITextFieldDelegate>
2)设置代理(下面的self都是输入框所在的父view)
textField.delegate = self;
3)实现UITextFieldDelegate的三个方法即可:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
[textField resignFirstResponder];
return YES;
}
/***下面是全屏的一个view, view上有子控件 textField的使用方法***/
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect frame = textField.frame;
int offset = frame.origin.y + 32 - (self.frame.size.height - 256.0);//键盘高度256, textField高度32
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
//将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
if(offset > 0)
self.frame = CGRectMake(0.0f, -offset, self.frame.size.width, self.frame.size.height);
[UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
self.frame =CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}
/***下面是全屏的一个view, view上有tableView, 每个tableViewCell有子控件 textField的使用方法***/
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect frame = textField.frame;
int index = (int)(textField.tag - 0x1000);
//30为textField的高度, (index - 1)为前面有几个cell, 90为tableView的y,即输入框底部距self.view的高度减去键盘的顶部距self.view的高度
int offset = frame.origin.y + (index - 1) * 50 + 30 + 90 - (self.view.frame.size.height - 256.0);//键盘高度256
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
//将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
if(offset > 0)
self.infoList.frame = CGRectMake(10.0f, 90 - offset, self.infoList.frame.size.width, self.infoList.frame.size.height);
[UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
self.infoList.frame =CGRectMake(10, 90, [UIScreen mainScreen].bounds.size.width - 20, 300);
{
CGRect frame = textField.frame;
int index = (int)(textField.tag - 0x1000);
//30为textField的高度, (index - 1)为前面有几个cell, 90为tableView的y,即输入框底部距self.view的高度减去键盘的顶部距self.view的高度
int offset = frame.origin.y + (index - 1) * 50 + 30 + 90 - (self.view.frame.size.height - 256.0);//键盘高度256
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
//将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
if(offset > 0)
self.infoList.frame = CGRectMake(10.0f, 90 - offset, self.infoList.frame.size.width, self.infoList.frame.size.height);
[UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
self.infoList.frame =CGRectMake(10, 90, [UIScreen mainScreen].bounds.size.width - 20, 300);
}
效果截图: