ios - 无法使用 KVO 在 UIView 动画期间获取新值

标签 ios objective-c uiviewanimation key-value-observing

我想像这样在 UIView 动画期间获取 scrollView 的 contentOffsetcontentInset:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    [self.window makeKeyAndVisible];

    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(100, 100, 120, 100)];
    scrollView.backgroundColor = [UIColor grayColor];
    scrollView.contentSize = scrollView.frame.size;

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"hello world";

    [scrollView addSubview:label];

    UIViewController *vc = [[UIViewController alloc] init];
    [vc.view addSubview:scrollView];

    [scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:NULL];
    [scrollView addObserver:self forKeyPath:@"contentInset" options:NSKeyValueObservingOptionNew context:NULL];

    [UIView animateWithDuration:2 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        scrollView.contentInset = UIEdgeInsetsMake(50, 0, 0, 0);
        scrollView.contentOffset = CGPointMake(0, -50);
    } completion:nil];

    self.window.rootViewController = vc;

    return YES;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentOffset"]) {
        NSLog(@"offset:%@", [change valueForKey:NSKeyValueChangeNewKey]);
    }
    if ([keyPath isEqualToString:@"contentInset"]) {
        NSLog(@"inset:%@", [change valueForKey:NSKeyValueChangeNewKey]);
    }
}

不幸的是,在制作动画时没有输出,我是不是错过了什么,或者 KVO 在制作 UIView 动画时不起作用?

最佳答案

您的结论是正确的,即 KVO 在 UIView 动画期间不起作用。

这是因为你的 ScrollView 的实际属性在动画过程中没有改变:Core Animation 只是简单地动画一个位图,它代表 ScrollView 从它的开始状态移动到它的结束状态。它不会在运行时更新底层对象的属性,因此在动画运行期间 KVO 状态不会发生变化。

不幸的是,出于同样的原因,如果您尝试通过 UIScrollViewDelegate 协议(protocol)方法观察 contentOffset 和 inset,情况也是如此。

Apple 指南 here 中可以找到更深入(且相当难以理解)的解释.

关于ios - 无法使用 KVO 在 UIView 动画期间获取新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18170624/

相关文章:

ios - 解析聊天室 - 将 NS 数组转换为 NSMutableArray 以在 TableView 上显示

ios - 添加自定义控件后 ScrollView 不起作用

iphone - 使用 [self 方法] 或 @selector(方法)?

ios - 自定义 CALayer 动画

ios - 以编程方式为具有约束的 UIImageView(View)从 A 点到 B 点设置动画

ios - UITableViewCells 的手势识别器

objective-c - 继承的属性不起作用

objective-c - 如何连接到无线网络

ios - UIButton 动画被跳过

ios - 带有函数的 NSSortDescriptor