它应该很简单:
- (void)setScrollView:(UIScrollView *)scrollView bottomOffsetToView:(UIView *)view
{
scrollView.contentOffset = CGPointMake(0, view.frame.origin.y + view.frame.size.height - 216);
}
然后在您的代码中将自己设置为 UITextFieldDelegate 并实现:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
self.currentTextField = textField;
}
更新 :
你在这里问两个不同的事情。对于键盘通知的键盘注册(viewWillAppear
例如):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
然后根据键盘大小更改滚动视图框架:
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
self.scrollView.frame = (CGRect){self.scrollView.frame.origin,(CGSize){self.scrollView.frame.size.width,self.scrollView.frame.size.height-kbSize.height);
if (self.currentTextField != nil)
{
[self setScrollView:self.scrollView bottomOffsetToView:self.currentTextField];
}
}
keyboardWasHidden 的行为相同(重置初始帧),不要忘记删除 viewDidDisappear 中的 Observer。