【发布时间】:2014-11-30 18:54:35
【问题描述】:
当我的自定义 UIView 子类的绝对框架(不仅是相对于其父级的框架,而且当 superview/grandsuperview 等的框架发生变化,导致我的视图的框架发生变化)在屏幕上发生变化时,我需要得到通知。我尝试在-(void)didMoveToSuperview、-(void)didMoveToWindow 处获取绝对帧convertRect:toView:,并且我还在两者中添加了此代码:
UIView *view = self.superview;
while (view) {
[view addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
[view addObserver:self forKeyPath:@"superview" options:NSKeyValueObservingOptionNew context:nil];
view = view.superview;
}
它们都被调用了几次(这没关系),但我得到的坐标不正确。 在所有设置实际可见框架的代码之后,还有其他东西运行。我通过将其放入我的代码来验证这一点:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
CGRect globalFrame = [view.superview.superview convertRect:view.superview.frame toView:[[view.delegate tutorialView] superview]];
NSLog(@"after 2 sec %@", NSStringFromCGRect(globalFrame));
if([view.delegate respondsToSelector:@selector(attachedViewFrameDidChange:)]){
[view.delegate attachedViewFrameDidChange:globalFrame];
}
});
忘记view.delegate 和我的其他自定义参数/对象/方法。两秒钟后,我在globalFrame 中得到了正确的值。我在-(void)didMoveToSuperview、-(void)didMoveToWindow、-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 中有完全相同的代码,它们都以不正确的帧值调用(当我调用convertRect:toView: 时得到不正确的值。为什么会这样,我怎样才能得到两秒钟后得到的绝对/真实帧值(我在屏幕上看到的),显然没有等待?
【问题讨论】:
标签: ios objective-c uiview frame