Attempt to present on whose view is not in the window hierarchy!

本文详细阐述了一个在ViewController中直接跳转到另一个ViewController导致窗口层次结构混乱的问题,并提供了解决方案。通过将跳转操作从viewDidLoad移至viewDidAppear,避免了错误的层级显示。解决方案确保了应用程序的稳定性和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Attempt to present on whose view is not in the window hierarchy!

##

- (void)viewDidLoad {
    [super viewDidLoad];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
    UIViewController *controller = [story instantiateViewControllerWithIdentifier:@"RootViewController"];
    [self presentViewController:controller animated:YES completion:nil];
}

上面代码中的问题是在controller a的viewDidLoad里面直接跳转controller b,然后导致在显示controller b的时候也调用了controller a来显示,然后发现这个window的层次结构就错乱了。
参考:stackoverflow给出的回答

我的解决方案是:等到viewcontroller 显示完之后再跳转

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
    UIViewController *controller = [story instantiateViewControllerWithIdentifier:@"RootViewController"];
    [self presentViewController:controller animated:YES completion:nil];
}
这个错误信息通常出现在使用React Native开发iOS应用时,特别是涉及到图片选择器(如PHPickerViewController)时。这个错误提示表明应用试图在一个已经存在的模态视图控制器(<RCTModalHostViewController)上呈现一个新的视图控制器(PHPickerViewController),这会导致冲突。 以下是一些可能的解决方案: 1. **确保视图控制器正确呈现**: 确保在呈现PHPickerViewController之前,没有其他模态视图控制器正在显示。可以在呈现新的视图控制器之前,先关闭所有其他模态视图控制器。 2. **使用React Native的Modal组件**: 使用React Native的Modal组件来呈现PHPickerViewController,这样可以确保视图控制器的层级关系正确。 ```javascript import { Modal, View, Button, Platform } from 'react-native'; import { PHPickerViewController } from 'react-native-ui-lib'; const ImagePickerModal = ({ isVisible, onClose, onSelect }) => { const openPicker = () => { const picker = new PHPickerViewController({ filter: PHPickerFilter.images, selectionLimit: 0, }); picker.setDelegate({ pickerDidFinishPicking: (items) => { onSelect(items); picker.dismiss(animated: true, completion: null); }, }); picker.presentAnimated(true, null); }; return ( <Modal visible={isVisible} transparent={true}> <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Button title="Open Picker" onPress={openPicker} /> <Button title="Close" onPress={onClose} /> </View> </Modal> ); }; export default ImagePickerModal; ``` 3. **检查生命周期方法**: 确保在适当的生命周期方法中呈现和关闭视图控制器。例如,在组件卸载时,确保所有模态视图控制器都已关闭。 4. **调试和日志记录**: 使用日志记录来调试问题,确保视图控制器在正确的时机呈现和关闭。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值