SwiftUI中keyWindow弃用警告及约束崩溃问题求助
一、keyWindow弃用警告及崩溃修复
你当前用的UIApplication.shared.keyWindow!有两个致命问题:
- iOS13+弃用警告:多场景应用下
keyWindow无法精准返回当前活跃窗口,苹果已标记该API弃用; - 强制解包崩溃:
!强制解包会在窗口获取失败时直接触发崩溃。
替代方案
先给UIApplication写个扩展,安全获取当前活跃窗口:
extension UIApplication { var currentActiveWindow: UIWindow? { connectedScenes .compactMap { $0 as? UIWindowScene } .first? .windows .first { $0.isKeyWindow } } }
再修改你的offset代码,用空合运算符避免崩溃:
.offset(y: originTextField.y + (UIApplication.shared.currentActiveWindow?.safeAreaInsets.top ?? 0) + 52)
二、导航栏约束冲突修复
约束冲突日志翻译
以下约束列表中至少有一个是冗余或错误的。
排查步骤:
(1) 逐个检查约束,定位不符合预期的条目;
(2) 找到添加该约束的代码并修正。
(
"<NSLayoutConstraint:0x28396b700 'BIB_Leading_Leading' H:|-(0)-[_UIModernBarButton:0x103fad930] (已激活,父视图:_UIButtonBarButton:0x103facda0 )>",
"<NSLayoutConstraint:0x28397c460 'UINav_static_button_horiz_position' _UIModernBarButton:0x103fad930.leading == UIViewLayoutMarginsGuide.leading (已激活)>",
"<NSLayoutConstraint:0x28397c4b0 'UINavItemContentGuide-leading' H:[_UIButtonBarButton:0x103facda0]-(6)-[UINavigationBarItemContentLayoutGuide] (已激活)>",
"<NSLayoutConstraint:0x283969f40 'UINavItemContentGuide-trailing' UINavigationBarItemContentLayoutGuide.trailing == _UINavigationBarContentView:0x103fabfd0.trailing (已激活)>",
"<NSLayoutConstraint:0x2839799a0 'UIView-Encapsulated-Layout-Width' _UINavigationBarContentView:0x103fabfd0.width == 0 (已激活)>",
"<NSLayoutConstraint:0x28396a300 'UIView-leftMargin-guide-constraint' H:|-(8)-UIViewLayoutMarginsGuide (已激活,父视图:_UINavigationBarContentView:0x103fabfd0 )>
)系统将尝试打破以下约束以恢复布局:
<NSLayoutConstraint:0x28396b700 'BIB_Leading_Leading' H:|-(0)-[_UIModernBarButton:0x103fad930] (已激活,父视图:_UIButtonBarButton:0x103facda0 )>"
问题根源与修复
核心问题是_UINavigationBarContentView.width == 0这个约束——导航栏内容视图被强制设为0宽度,直接引发后续按钮的布局冲突。
修复建议:
- 检查自定义导航栏代码,是否错误设置了宽度为0的约束;
- 如果用SwiftUI的
NavigationStack/NavigationView,避免对导航栏进行非法的frame修改; - 若涉及UIKit与SwiftUI交互(如
UIViewControllerRepresentable),检查是否传递了错误的布局参数; - 给导航栏所在的父视图设置明确的宽度约束,确保导航栏内容视图能获取到正确的宽度值。
内容的提问来源于stack exchange,提问作者EN_Tech

