我希望在UIView动画中获得scrollView的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动画时不起作用吗?
答案 0 :(得分:3)
你的结论是正确的,KVO在UIView
动画期间不起作用。
这是因为你的scrollview的实际属性在动画过程中没有改变:Core Animation只是动画一个位图,它代表从开始状态到结束状态的scrollview。它不会更新底层对象的属性,因此当动画在飞行中时没有KVO状态发生变化。
不幸的是,如果您尝试通过UIScrollViewDelegate
协议方法观察contentOffset和inset,原因相同。
Apple的指南here中可以找到更深入(且相当难以理解)的解释。