我很困惑willMoveToWindow:
,我遇到了一个问题,它在视图上被调用了两次。
当一个新的视图控制器被推到一个UINavigationController
,
willMoveToWindow:
在具有值的现有视图上调用nil
(有意义,因为视图正在移出屏幕)
在那之后,再次调用该方法willMoveToWindow:
,但现在使用原始窗口。
我最初的想法是window
在原始方法启动之前调动和调用属性。
为了安全起见,我创建了一个小型示例项目并确认了相同的行为。
基本上我需要一种方法来确定视图不在window
(因为当视图移动到实际上不应该运行的窗口时我正在触发逻辑(至少不是两次))
作为参考,可以使用以下代码重现该问题:
@implementation RandomView
-(void)willMoveToWindow:(UIWindow *)newWindow {
// when the new view controller is pushed -
//the method is called twice on the existing view (on the screen view)-
//first time will be called with nil -
//second time with the original window
NSLog(@"********%s <RandomView %p> <Window %p>",__PRETTY_FUNCTION__,self,newWindow);
}
-(void)didMoveToWindow {
NSLog(@"********%s <RandomView %p> <Window %p>",__PRETTY_FUNCTION__,self,self.window);
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
RandomView *k = [[RandomView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:k];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
ViewController *vc = [[ViewController alloc] init];
[self.navigationController pushViewController:vc animated:YES];
});
});
//[self becomeFirstResponder];
}
@end
编辑控制台
[RandomView willMoveToWindow:] <RandomView 0x7f8b21e16630> <Window 0x7f8b21d220d0>
[RandomView didMoveToWindow] <RandomView 0x7f8b21e16630> <Window 0x7f8b21d220d0>
//THIS IS THE ISSUE
[RandomView willMoveToWindow:] <RandomView 0x7f8b21e16630> <Window 0x0>
[RandomView didMoveToWindow] <RandomView 0x7f8b21e16630> <Window 0x0>
[RandomView willMoveToWindow:] <RandomView 0x7f8b21e16630> <Window 0x7f8b21d220d0>
[RandomView didMoveToWindow] <RandomView 0x7f8b21e16630> <Window 0x7f8b21d220d0>
[RandomView willMoveToWindow:] <RandomView 0x7f8b21e16630> <Window 0x0>
[RandomView didMoveToWindow] <RandomView 0x7f8b21e16630> <Window 0x0>