以前的做法和这个比起来简直就是xxxx,今天看官方的参考库又学了一招~
以前的实现效果和这个是一样,不过代码上比这个多了点
程序清单5-1 处理键盘通告
// Call this method somewhere in your view controller setup code. |
- (void)registerForKeyboardNotifications |
{ |
[[NSNotificationCenter defaultCenter] addObserver:self |
selector:@selector(keyboardWasShown:) |
name:UIKeyboardDidShowNotification object:nil]; |
[[NSNotificationCenter defaultCenter] addObserver:self |
selector:@selector(keyboardWasHidden:) |
name:UIKeyboardDidHideNotification object:nil]; |
} |
// Called when the UIKeyboardDidShowNotification is sent. |
- (void)keyboardWasShown:(NSNotification*)aNotification |
{ |
if (keyboardShown) |
return; |
NSDictionary* info = [aNotification userInfo]; |
// Get the size of the keyboard. |
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey]; |
CGSize keyboardSize = [aValue CGRectValue].size; |
// Resize the scroll view (which is the root view of the window) |
CGRect viewFrame = [scrollView frame]; |
viewFrame.size.height -= keyboardSize.height; |
scrollView.frame = viewFrame; |
// Scroll the active text field into view. |
CGRect textFieldRect = [activeField frame]; |
[scrollView scrollRectToVisible:textFieldRect animated:YES]; |
keyboardShown = YES; |
} |
// Called when the UIKeyboardDidHideNotification is sent |
- (void)keyboardWasHidden:(NSNotification*)aNotification |
{ |
NSDictionary* info = [aNotification userInfo]; |
// Get the size of the keyboard. |
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey]; |
CGSize keyboardSize = [aValue CGRectValue].size; |
// Reset the height of the scroll view to its original value |
CGRect viewFrame = [scrollView frame]; |
viewFrame.size.height += keyboardSize.height; |
scrollView.frame = viewFrame; |
keyboardShown = NO; |
} |
上面程序清单中的keyboardShown
变量是一个布尔值,用于跟踪键盘是否可见。如果您的用户界面有多个文本输入框,则用户可能触击其中的任意一个进行编辑。发生这种情况时,虽然键盘并不消失,但是每次开始编辑新的文本框时,系统都会产生UIKeyboardDidShowNotification
通告。您可以通过跟踪键盘是否确实被隐藏来避免多次减少滚动视图的尺寸。
程序清单5-2显示了一些额外的代码,视图控制器用这些代码来设置和清理之前例子中的activeField
变量。在初始化时,界面中的每个文本框都将视图控制器设置为自己的委托。因此,当文本编辑框被激活的时候,这些方法就会被调用。更多关于文本框及其委托通告的信息,请参见UITextField类参考。
程序清单5-2 跟踪活动文本框的方法
- (void)textFieldDidBeginEditing:(UITextField *)textField |
{ |
activeField = textField; |
} |
- (void)textFieldDidEndEditing:(UITextField *)textField |
{ |
activeField = nil; |
} |