首先你要确保所有 textField 的委托都设置为 self(意味着你的 viewController)
Ex. [myTextField setDelegate:self];// you can also set the delegate in Storyboard or xib directly
然后在你的类实现中添加一个实例变量 -
@implementation myViewController
{
UITextField *activeField;
}
然后简单的实现如下方法
在你的 textFieldShouldBeginEditing 中,设置 activeField
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
activeField = textField; // HERE get reference of your active field
return true;
}
为所有处理提供了一个非常好的方法
CGRectContainsRect
if (!CGRectContainsRect(viewableAreaFrame, activeTextFieldFrame))
{
/*Scroll or move view up*/
}
在你的keyboardWillShow方法中实现如下
EX.
- (void)keyboardWillShow:(NSNotification *)notification
{
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
float viewWidth = self.view.frame.size.width;
float viewHeight = self.view.frame.size.height;
CGRect viewableAreaFrame = CGRectMake(0.0, 0.0, viewWidth, viewHeight - keyboardHeight);
CGRect activeTextFieldFrame = [activeTextField frame];
if (!CGRectContainsRect(viewableAreaFrame, activeTextFieldFrame))
{
/*Scroll or move view up*/
[UIView animateWithDuration:0.3 animations:^{
CGRect f = self.view.frame;
f.origin.y = -keyboardSize.height;
self.view.frame = f;
}];
}
}