摘要
childVC添加到parentVC中childVC.view为什么?
情况
我刚刚遇到了一种奇怪的行为,我想知道它是正常的还是错误的。
我有一个视图控制器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();错误
那么我就有了一个错误:
*由于UIViewControllerHierarchyIn稠度异常终止应用程序,原因:“子视图控制器:应该有父视图控制器:(Null),但实际父程序为:”*第一次抛出调用堆栈:(0 CoreFoundation 0x0260b466 __exceptionPreprocess + 182 1 libobjc.A.dylib ) 0x02290a97 objc_exception_throw +442 CoreFoundation 0x0260b38d +NSException引发:格式:+ 141 3 UIKit 0x01136710 _associatedViewControllerForwardsAppearanceCallbacks:performHierarchyCheck:isRoot:+ 352 4 UIKit 0x01136b13 -UIView(层次结构) _willMoveToWindow:withAncestorView:+ 285 5 UIKit 0x0114330a -UIView(内部) _addSubview:positioned:relativeTo:+ 511 6 UIKit 0x01136252 -UIView(层次) 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();也许这会有很大的不同。
发布于 2019-12-05 23:05:18
今天,在使用UIViewControllerAnimatedTransitioning实现自定义转换时,我遇到了同样的问题。问题是,当我尝试快照子视图控制器时,其父控件还不是视图层次结构的一部分。
解决方案是在尝试快照子视图之前确保父视图已添加到视图层次结构中。在我的例子中,我只需要首先将" to“视图控制器添加到transitionContext.containerView中。
从您的代码片段中,我无法判断您何时尝试拍摄快照。但是如果是在viewDidAppear()之前,它可能就行不通了。
发布于 2020-03-05 07:59:54
在从父控件中删除子视图控制器视图之前,我在使用view.snapshotView(afterScreenUpdates: true)捕获子视图控制器视图时遇到了此崩溃。
对我来说,把false传给afterScreenUpdates解决了这个问题。
发布于 2016-05-15 10:41:10
也许您的父视图控制器正在被解除分配,因此出现了异常消息中的(null)?
https://stackoverflow.com/questions/30531076
复制相似问题