简体   繁体   English

iOS:动画在observeValueForKeyPath中不起作用

[英]iOS: Animation Not working in observeValueForKeyPath

I used KVO to observe changes in a frame and set another frame accordingly 我用KVO 观察了一个框架中的变化并相应地设置了另一个框架

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:KeyPathForFrameBeingObserved]) {
         [UIView animateWithDuration:1 animations:^{
            CGRect frame = [self playWithFrame:viewBeingMonitored.frame];
            self.viewToAnimate.frame = frame;
         }];
    }
}

Code in the animation block is executed but animation is not working, I suspected that repeated calls to animation method could cause this but using log messages I found that animation is not working even for a single call, can anyone explain that ? 动画块中的代码已执行,但动画无法正常工作,我怀疑重复调用动画方法可能会导致这种情况,但是使用日志消息后,我发现即使一次调用动画也无法正常工作,有人可以解释吗?

iPad 2/(iOS8.4) iPad 2 /(iOS8.4)

  • I have tried including the animation method call in dispatch_async(dispatch_get_main_queue(), ^{ ... }); 我尝试将动画方法调用包含在dispatch_async(dispatch_get_main_queue(), ^{ ... }); but animation still not working. 但动画仍然无法正常工作。
  • I have tried pushing the observed changes in queue and delaying the animation method for a second using dispatch_after to run it only using the last element in the queue to avoid repeated calls but didn't work. 我尝试将观察到的更改推送到队列中,并使用dispatch_after将动画方法延迟一秒钟,以便仅使用队列中的最后一个元素来运行它,以避免重复调用,但无效。
  • KVO is working perfectly (adding the observer is already handled), but the code in the animation block is executed without animation. KVO运行良好(添加了观察器,但已处理完毕),但是动画块中的代码是在没有动画的情况下执行的。

It seems like you're trying to observe the property of an UIKit object. 似乎您正在尝试观察UIKit对象的属性。 Keep in mind that: 请记住:

... the classes of the UIKit framework generally do not support KVO ... ... UIKit框架的类通常不支持KVO ...

Source: https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/KVO.html 资料来源: https : //developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/KVO.html

So, you have to check if your observeValueForKeyPath:ofObject:change:context: is calling in fact. 因此,您必须检查您的observeValueForKeyPath:ofObject:change:context:实际上是否正在调用。

This is an older question but I thought I would answer in case someone else is reading this. 这是一个比较老的问题,但是我想我会回答其他人正在阅读的情况。 You will need to call setFrame to set the frame of the animation instead of the simple assignment. 您将需要调用setFrame来设置动画的帧,而不是简单的分配。

CGRect frame = [self playWithFrame:viewBeingMonitored.frame]; CGRect frame = [self playWithFrame:viewBeingMonitored.frame]; [self.viewToAnimate setFrame:frame]; [self.viewToAnimate setFrame:frame];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM