3

我想像这样在 UIView 动画期间获得滚动contentOffset视图contentInset

- (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 动画时不起作用?

4

1 回答 1

4

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

这是因为您的滚动视图的实际属性在动画过程中没有改变:核心动画只是为一个位图制作动画,该位图表示滚动视图从其开始状态移动到其结束状态。它不会在运行时更新底层对象的属性,因此在动画运行期间不会更改 KVO 状态。

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

可以在此处的 Apple 指南中找到更深入(且相当难以理解)的解释。

于 2013-08-11T18:08:40.753 回答