我有一个包含多个文本字段和文本视图的表单。显示keyboad时,我更新了scrollview框架以防止文本字段隐藏在键盘下。 我确实关注this question并实施了类似的解决方案。
它实际上适用于uitextfields,但不适用于uitextviews。
当键盘显示时,scrollview高度会降低键盘高度,然后滚动到聚焦的uitextfield。但是如果关注的项目是uitextview,它就不会滚动,而uiscrollview的高度会降低。
我的scrollview的IB截图;
https://www.dropbox.com/s/a1iblh6nsdqy34t/Screenshot%202014-05-30%2021.44.32.png https://www.dropbox.com/s/o2h8avt5w82r5eo/Screenshot%202014-05-30%2021.45.19.png
这是代码;
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
通知处理程序;
-(void)keyboardWillShow:(NSNotification *)n {
if(keyboardUp)
return;
NSDictionary* userInfo = [n userInfo];
// get the size of the keyboard
CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
const int movementDistance = -keyboardSize.height - keyboardPaddingToScrollView;
const float movementDuration = 0.30f;
int movement = movementDistance;
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
CGRect contentSize = self.view.frame;
contentSize.size.height += movementDistance;
[self.view setFrame:contentSize];
[UIView commitAnimations];
}
-(void)keyboardDidShow:(NSNotification *)n {
keyboardUp = true;
NSLog(NSStringFromCGRect(self.view.frame));
}
-(void)keyboardWillHide:(NSNotification *)n {
if(!keyboardUp)
return;
NSDictionary* userInfo = [n userInfo];
// get the size of the keyboard
CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
const int movementDistance = keyboardSize.height + keyboardPaddingToScrollView;
const float movementDuration = 0.30f;
int movement = movementDistance;
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
CGRect contentSize = self.view.frame;
contentSize.size.height += movementDistance;
self.view.frame = contentSize;
[UIView commitAnimations];
}
-(void)keyboardDidHide:(NSNotification *)n {
keyboardUp = false;
}