当键盘出现的时候,如何让UITextField自动上移
对于iPhone界面控件的操作应该算是开发中必备的能力。键盘出现的时候上移相关的控件算是常见的需求,但是从这么多人问这个问题就可以看出,还是有很多人对这些需求的实现方式有疑问。
对于这个问题,主要是通过增加对键盘出现和消失的相应的Notification,然后在键盘出现和消息的时候,通过设置相关控件的frame来实现。相关代码如下,来源自stackoverflow。
-(void)textFieldDidBeginEditing:(UITextField *)sender{ if ([sender isEqual:_textField]) { //move the main view, so that the keyboard does not hide it. if (self.view.frame.origin.y >= 0) { [self setViewMovedUp:YES]; } }}//method to move the view up/down whenever the keyboard is shown/dismissed-(void)setViewMovedUp:(BOOL)movedUp{ [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.5]; // if you want to slide up the view CGRect rect = self.view.frame; if (movedUp) { // 1. move the view's origin up so that the text field that will be hidden come above the keyboard // 2. increase the size of the view so that the area behind the keyboard is covered up. rect.origin.y -= kOFFSET_FOR_KEYBOARD; rect.size.height += kOFFSET_FOR_KEYBOARD; } else { // revert back to the normal state. rect.origin.y += kOFFSET_FOR_KEYBOARD; rect.size.height -= kOFFSET_FOR_KEYBOARD; } self.view.frame = rect; [UIView commitAnimations];}- (void)keyboardWillShow:(NSNotification *)notif{ //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately if ([_textField isFirstResponder] && self.view.frame.origin.y >= 0) { [self setViewMovedUp:YES]; } else if (![_textField isFirstResponder] && self.view.frame.origin.y < 0) { [self setViewMovedUp:NO]; }}- (void)viewWillAppear:(BOOL)animated{ // register for keyboard notifications [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:self.view.window];}- (void)viewWillDisappear:(BOOL)animated{ // unregister for keyboard notifications while not visible. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];}