3

i want to get scrollView's contentOffset and contentInset during UIView animation like this:

- (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]);
    }
}

unfortunately there is no output while animating, am i miss something or KVO just doesn't work when doing UIView animating?

limboy
  • 3,879
  • 7
  • 37
  • 53

1 Answers1

4

You're correct in your conclusion that KVO doesn't work during UIView animations.

This is because your scrollview's actual properties are not changing during the course of the animation: Core Animation is simply animating a bitmap which represents the scrollview moving from its start state to its end state. It's not updating the underlying object's properties as it goes, hence no KVO state changes while the animation is in-flight.

The same is unfortunately true if you attempt to observe contentOffset and inset via UIScrollViewDelegate protocol methods, for the same reasons.

A more in-depth (and fairly impenetrable) explanation can be found in Apple's guide here.

davidf2281
  • 1,319
  • 12
  • 20