添加UINavigationController时崩溃问题(Swift)
看起来你遇到的崩溃核心是类型转换失败,同时还有一个库内部的traitCollection重写警告,我来一步步帮你解决:
一、修复崩溃的核心问题:类型转换错误
错误日志里的这条信息是关键:
Could not cast value of type 'UINavigationController' (0x1049b1338) to 'AppstoreTransition.CardsViewController' (0x1049b1308).
这说明你在Storyboard中给"type2"这个标识符绑定的是UINavigationController,而不是直接的Type2ViewController。所以当你执行instantiateViewController(withIdentifier: "type2") as! Type2ViewController时,实际拿到的是导航控制器,强制转成Type2ViewController自然会崩溃。
解决方法二选一:
调整代码适配导航控制器:
修改你的实例化代码,先获取导航控制器,再取出它的根控制器:let storyboard = UIStoryboard(name: "Main", bundle: nil) // 先转成UINavigationController let navController = storyboard.instantiateViewController(withIdentifier: "type2") as! UINavigationController // 再获取根控制器作为Type2ViewController let viewController = navController.rootViewController as! Type2ViewController // 后续代码保持不变... cell.settings.cardContainerInsets = UIEdgeInsets(top: 8.0, left: 16.0, bottom: 8.0, right: 16.0) cell.settings.isEnabledBottomClose = bottomDismiss transition = CardTransition(cell: cell, settings: cell.settings) viewController.settings = cell.settings viewController.transitioningDelegate = transition viewController.subtitle = "Bottom dismissible" viewController.background = UIImage(named: "type2-bg-bottom") // 注意:这里要把导航控制器设置为自定义模态样式,而不是子控制器 navController.modalPresentationStyle = .custom presentExpansion(navController, cell: cell, animated: true)修改Storyboard的标识符绑定:
如果你的Type2ViewController不需要被导航控制器包裹,直接在Storyboard里把"type2"标识符绑定到Type2ViewController本身(而不是它外层的UINavigationController),这样原代码的类型转换就会正常工作。
二、处理traitCollection重写警告
日志里的这条警告:
Class AppstoreTransition.CardPresentationController overrides the -traitCollection getter, which is not supported. If you're trying to override traits, you must use the appropriate API.
这是AppstoreTransition库内部的实现问题,苹果不允许直接重写traitCollection的getter方法,正确的做法是使用setOverrideTraitCollection(_:forChildViewController:)来修改子控制器的trait集合。
你可以:
- 忽略这个警告(它不会直接导致崩溃);
- 给该库提交Issue反馈这个问题;
- 如果有能力的话,自己修改库的
CardPresentationController代码,替换掉重写traitCollection的逻辑,改用苹果推荐的API。
内容的提问来源于stack exchange,提问作者Bartek

