摘要
- 将
childVC
添加到parentVC
- 快照
childVC.view
- 出现问题。
为什么?
情况
我刚遇到一个奇怪的行为,想知道它是正常的还是一个bug。
我有一个视图控制器childVC
,它是parentVC
的子代。创建父/子关系时,我的代码如下:
[parentVC addChildViewController:childVC] ;
[parentVC.view addSubview:childVC.view] ;
[childVC didMoveToParentViewController: parentVC] ;
在稍后的几行中,我想创建childVC.view
的快照。我的代码是:
UIView * view = childVC.view ;
UIGraphicsBeginImageContextWithOptions(view.contentSize, NO, 0);
{
[...]
[view drawViewHierarchyInRect:view.bounds
afterScreenUpdates:YES];
image = UIGraphicsGetImageFromCurrentImageContext();
[...]
}
UIGraphicsEndImageContext();
Bug
出现以下错误:
* Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'child view controller: should have parent view controller:(null) but actual parent is:' * First throw call stack: ( 0 CoreFoundation 0x0260b466 __exceptionPreprocess + 182 1 libobjc.A.dylib
0x02290a97 objc_exception_throw + 44 2 CoreFoundation
0x0260b38d +[NSException raise:format:] + 141 3 UIKit
0x01136710 -[UIView(Hierarchy) _associatedViewControllerForwardsAppearanceCallbacks:performHierarchyCheck:isRoot:] + 352 4 UIKit 0x01136b13 -[UIView(Hierarchy) _willMoveToWindow:withAncestorView:] + 285 5 UIKit 0x0114330a -[UIView(Internal) _addSubview:positioned:relativeTo:] + 511 6 UIKit 0x01136252 -[UIView(Hierarchy) addSubview:] + 56 7 UIKit
0x0114ab0e +[_UIReplicantView _pendingSnapshotOfTarget:snapshotBlock:] + 584 8 UIKit 0x011312fe -[UIView drawViewHierarchyInRect:afterScreenUpdates:] + 287
问题
为什么会这样?我该如何解决这个问题?
更多细节
实际上,childVC.view
是一个UIScrollView
,截图的代码如下:
UIScrollView * scrollView = (UIScrollView *)childVC.view;
UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, NO, 0);
{
CGPoint savedContentOffset = scrollView.contentOffset;
CGRect savedFrame = scrollView.frame;
scrollView.contentOffset = CGPointZero;
scrollView.frame = CGRectMake(0,
0,
scrollView.contentSize.width,
scrollView.contentSize.height);
[scrollView drawViewHierarchyInRect:scrollView.bounds
afterScreenUpdates:YES];
image = UIGraphicsGetImageFromCurrentImageContext();
scrollView.contentOffset = savedContentOffset;
scrollView.frame = savedFrame;
}
UIGraphicsEndImageContext();
也许那会有很大的区别。
view.window == nil
)。 - rabbitinspace