我正在使用以下代码根据键盘移动为 View 的位置设置动画。该代码在 iOS 7 下运行良好,但在 iOS 8 下会导致奇怪的行为:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
- (void) keyboardWillShow:(NSNotification*) aNotification {
NSDictionary* keyboardInfo = [aNotification userInfo];
NSTimeInterval time = [keyboardInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationCurve curve = [keyboardInfo[UIKeyboardAnimationCurveUserInfoKey] intValue];
CGRect keyboardFrameEnd = [[keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
double offset = keyboardFrameEnd.size.width > keyboardFrameEnd.size.height ? keyboardFrameEnd.size.height : keyboardFrameEnd.size.width;
[UIView beginAnimations:@"moveWindow" context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationCurve:curve];
[UIView setAnimationDuration:time];
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + offset, self.frame.size.width, self.frame.size.height);
[UIView commitAnimations];
}
不幸的是,Is there a change to the behaviour of UIKeyboardWillShowNotification in iOS 8?中提到的答案和 iOS8: What's going on with moving views during keyboard transitions?是不可能的:
- 源代码库非常庞大且陈旧,既不使用 Storyboard也不使用自动布局功能。
- 我不想使用
UIKeyboardDidShowNotification
事件,因为键盘已经可见并且动画看起来很糟糕(但是,使用这种类型的通知时问题就消失了)。
奇怪的是,当在应用程序的第一个屏幕中使用该功能时,我发现问题消失了。进一步的测试表明,从之前的屏幕之一中删除 MKMapView
可以解决此问题。我三次检查了 MKMapView
是否被正确使用和处理。在执行上述代码之前,每个分配的实例都已消失。
经过数小时的测试和调试,我注意到在可视层次结构调试器 (How do I inspect the view hierarchy in iOS?) 中,在 UILayoutContainerView
和 UINavigationTransitionView
下添加了约束。当 MKMapView
控件从上一屏幕中移除时,这些约束将不存在。我尝试了 setTranslatesAutoresizingMaskIntoConstraints:
设置的所有可能组合,但还找不到任何解决方案。这是 iOS 8 本身的某种错误,还是有另一种方法可以使 View 与键盘一起动画化?
最佳答案
我不确定代码本身,但从有关这些动画方法的文档中...
Use of this method is discouraged in iOS 4.0 and later. You should use the block-based animation methods to specify your animations instead.
使 View 动画化的正确方法是...
[UIView animateWithDuration:time
delay:0
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + offset, self.frame.size.width, self.frame.size.height);
}
completion:nil];
编辑
好的,这不是 AutoLayout(我认为),但无论如何我都会把它留在这里,因为您需要更改它,我会等待问题中的更多信息。
关于ios - iOS 8 中 UIKeyboardWillShowNotification 事件的动画 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26467333/