原理:在鍵盤要出現之前調整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];
}
沒有留言:
張貼留言