使用多个 UITextField 时,声明一个 activeTextField 属性并将其分配给 didBegin 和 didEnd 委托调用会很有帮助
@property (nonatomic, assign) activeTextField;
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
self.activeTextField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
self.activeTextField = nil;
}
然后将scrollView调整为UITextField
在 viewDidLoad 中添加这个观察者
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification
object:nil];
实现这个方法
#define paddingAboveTextField 20
- (void)keyboardWasShown:(NSNotification *)notification
{
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
CGRect rectMinusKeyboard = self.view.frame;
rectMinusKeyboard.size.height -= keyboardSize.height;
if (!CGRectContainsPoint(rectMinusKeyboard, self.activeTextField.frame.origin) ) {
CGPoint scrollPoint = CGPointMake(0.0, self.activeTextField.frame.origin.y - (keyboardSize.height-paddingAboveTextField));
[scrollView setContentOffset:scrollPoint animated:YES];
}
}