我有一个包含文本字段和文本视图的UIScrollView。我有代码在键盘存在时向上移动文本字段,因此键盘不会覆盖文本字段。此代码在纵向视图中非常有用:
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
if(textField) {
[textField resignFirstResponder];
}
return NO;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField {
if (textField == self.nameField) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.3];
[UIView setAnimationBeginsFromCurrentState:YES];
self.view.frame = CGRectMake(self.view.frame.origin.x, (self.view.frame.origin.y - 90), self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
if (textField == self.nameField) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.3];
[UIView setAnimationBeginsFromCurrentState:YES];
self.view.frame = CGRectMake(self.view.frame.origin.x, (self.view.frame.origin.y + 90), self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
}
-(void)textViewDidBeginEditing:(UITextView *)textField {
if (textField == self.questionField) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.3];
[UIView setAnimationBeginsFromCurrentState:YES];
self.view.frame = CGRectMake(self.view.frame.origin.x, (self.view.frame.origin.y - 200), self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
}
-(void)textViewShouldEndEditing:(UITextView *)textField {
if (textField == self.questionField) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.3];
[UIView setAnimationBeginsFromCurrentState:YES];
UIInterfaceOrientation interfaceOrientation = self.interfaceOrientation;
self.view.frame = CGRectMake(self.view.frame.origin.x, (self.view.frame.origin.y + 200), self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
}
当我将iPhone模拟器旋转到横向视图时,这(不足为奇)不起作用。如何在横向视图和纵向视图中输入文本字段以便向上移动以便看到它?
此外,如果我在显示键盘时从横向旋转到纵向,则在关闭键盘后,滚动视图已向下移动到屏幕上,而不是排列在其原始位置。我怎么能避免这个?
答案 0 :(得分:2)
Apple的文档Managing the Keyboard在“移动位于键盘下方的内容”标题下显示了正确的方法。
您基本上将内容放在滚动视图上,并使用UIKeyboardDidShowNotification
和UIKeyboardWillHideNotification
通知来调整内容偏移量。
但是,代码有点不完整。键盘大小计算在横向模式下不起作用。要解决此问题,请将其替换为:
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
有了这个:
// Works in both portrait and landscape mode
CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
kbRect = [self.view convertRect:kbRect toView:nil];
CGSize kbSize = kbRect.size;