2016年1月11日 星期一

iOS筆記:自動調整View位置,讓UITextField不被鍵盤擋住

UITextField在螢幕的下方,一進入editing模式,鍵盤會跳出,此時UITextField是整個被鍵盤蓋住的。
原理:在鍵盤要出現之前調整VC.view的frame,整個往上移動到UITextField可以完整被看到。

加入UITextFieldDelegate 和一個變數 UITextField * editingTextField,指定textField.delegate


//加入觀察
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
//解除觀察
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                          name:UIKeyboardWillShowNotification
                                          object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                          name:UIKeyboardWillHideNotification
                                           object:nil];
}
//鍵盤出現/消失:調整view
- (void)keyboardWillShow:(NSNotification *)notification {
    
    NSDictionary* info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGPoint itemOrigin = [editingTextField convertPoint:editingTextField.frame.origin toView:self.view];
    CGFloat itemHeight = editingTextField.frame.size.height;
    CGRect visibleRect = self.view.bounds;
    visibleRect.size.height -= (keyboardSize.height+itemHeight);
    //BOOL tmp =CGRectContainsPoint(visibleRect, itemOrigin);
    
    //move up view if keyboard hide the textfield
    if (!CGRectContainsPoint(visibleRect, itemOrigin)){
        CGRect rect = self.view.frame;
        rect.origin.y -= keyboardSize.height;
        [UIView animateWithDuration:1.0 animations:^{
            self.view.frame = rect;
        }];
    }
}
- (void)keyboardWillHide:(NSNotification *)notification {
    CGRect rect = self.view.frame;
    rect.origin.y= 64; //64 =navgation bar height
    [UIView animateWithDuration:1.0 animations:^{
        self.view.frame = rect;
    }];
}
#pragma mark - textField Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    editingTextField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [textField resignFirstResponder];
}




沒有留言:

張貼留言