我知道这个问题已经被问过几次了。我了解在出现键盘时如何向上移动视图或文本字段,但是我遇到了一个我似乎无法弄清楚的故障。
我试图向上移动的视图位于 UIViewController 内,它充当两个视图的容器。这个容器本身就是一个滑动视图控制器内的视图(有点像 Facebook 实现的那个)。
当您第一次加载视图时,文本字段会向上移动,但是如果您转到不同的视图并返回,键盘会导致视图消失。
这是我用来向上移动视图的代码:
- (void) animateTextField:(BOOL)up {
const int movementDistance = 350; // tweak as needed
const float movementDuration = 0; // tweak as needed
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.sendingToolbar.frame = CGRectOffset(self.sendingToolbar.frame, 0, movement);
self.messagesTable.frame = CGRectOffset(self.messagesTable.frame, 0, movement);
//[splitController moveViewUp:up];
[UIView commitAnimations];
}
- (void)registerForKeyboardNotifications
{
NSLog(@"was this method called");
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
[self animateTextField:YES];
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
[self animateTextField:NO];
}
任何想法为什么会发生这种故障?谢谢
添加布尔值的建议以检查文本字段是否已经启动后,视图会在显示键盘时一直消失,而不仅仅是在您离开视图并返回时。这是修改后的方法:
- (void) animateTextField:(BOOL)up {
const int movementDistance = 350; // tweak as needed
const float movementDuration = 0; // tweak as needed
int movement = movementDistance;
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
if(textFieldIsUp && (up == YES)) {
NSLog(@"Case 1");
// Do nothing since text field is already up
}
else if(textFieldIsUp && (up == NO)) {
NSLog(@"Case 2");
// Move the text field down
self.sendingToolbar.frame = CGRectOffset(self.sendingToolbar.frame, 0, -movement);
self.messagesTable.frame = CGRectOffset(self.messagesTable.frame, 0, -movement);
textFieldIsUp = NO;
}
else if((textFieldIsUp == NO) && (up == YES)) {
NSLog(@"Case 3");
// Move the text field up
self.sendingToolbar.frame = CGRectOffset(self.sendingToolbar.frame, 0, movement);
self.messagesTable.frame = CGRectOffset(self.messagesTable.frame, 0, movement);
textFieldIsUp = YES;
}
else if((textFieldIsUp == NO) && (up == NO)) {
NSLog(@"Case 4");
// Do nothing since the text field is already down
}
else {
NSLog(@"Default");
// Default catch all case. Does nothing
}
[UIView commitAnimations];
}
以下是有关我的设置的更多详细信息:
视图控制器是应用程序的消息中心。视图控制器包含两个子视图,左侧的子视图是用于选择对话的菜单,右侧的菜单是包含该对话中消息的子视图。由于我希望从下往上加载消息,因此表格视图旋转了 180 度,单元格也向相反方向旋转了 180 度。此外,表格视图使用 NSTimer 每 5 秒重新加载一次,以便可以使用任何新消息更新消息。