使用 UIDevice.current.setValue() 在 SwiftUI 中锁定屏幕方向时崩溃

问题描述 投票:0回答:1

我的 SwiftUI 应用程序需要将某些视图锁定为横向,而将其他视图锁定为纵向,因此我使用了 this question 和其他人的流行 UIDevice.current.setValue() 技术。我对这个解决方案非常满意,但现在它似乎让我们的应用程序崩溃了。

例外是“doesNotRecognizeSelector”。下面的堆栈跟踪。

所以我将方向锁定在 SwiftUI View 的 onAppear 方法中:

onAppear {
       setStackScreen() // Function to make sure we are no longer in split screen, if we came in from a split-screen view
       UIDevice.current.setValue(UIInterfaceOrientation.portrait, forKey: "orientation")
       AppDelegate.orientationLock = .portrait
} 

对这里可能出现的问题有什么想法吗?这是崩溃消息。

最后的异常回溯:
0 CoreFoundation 0x180c4fd0c __exceptionPreprocess + 216 (NSException.m:200)
1 libobjc.A.dylib 0x198440ee4 objc_exception_throw + 56 (objc-exception.mm:565)
2 CoreFoundation 0x180d20750 -[NSObject(NSObject) doesNotRecognizeSelector:] + 140 (NSObject.m:147)
3 CoreFoundation 0x180be960c ___forwarding___ + 1472 (NSForwarding.m:3577)
4 CoreFoundation 0x180be881c _CF_forwarding_prep_0 + 92 (:-1)
5 基金会 0x182314740 _NSSetLongLongValueForKeyWithMethod + 76 (NSKeyValueAccessor.m:116)
6 基金会 0x1822f8fc8 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 312 (NSKeyValueCoding.m:437)
7 MyApp 0x10093bc04 MySwiftUIView.body.getter 中的闭包 #2 中的闭包 #2 + 480
8 SwiftUI 0x1882a76bc 闭包 #1 in _AppearanceActionModifier.MergedBox.update() + 92 (AppearanceActionModifier.swift:0)
9 SwiftUI 0x188326ea0 thunk for @escaping @callee_guaranteed () -> () + 20 (:0)
10 SwiftUI 0x18824cf24 ViewRendererHost.render(interval:updateDisplayList:) + 2336 (:0) 中的闭包 #1
ios swiftui crash uikit orientation
1个回答
0
投票

尽管这种锁定屏幕方向的方法在整个 StackOverflow 和其他地方都被推荐,但事实证明它是强烈反对的。在iOS16终于被限制了。我们的想法是,我们永远不应该弄乱 UIDevice 值,因为它们是只读的。根据one discussion:

“这个 setValue:forKey: 技术曾经有过效果,这是一个错误。 它不应该被任何应用程序使用。这种行为现在已经 已修复,因此 setValue:forKey: 技术不再有效。”

就这样吧。允许这个有用的解决方案是一个错误,现在已经被消灭了。我提出这个答案是希望它能让其他开发人员免于沮丧。还有其他看起来更值得信赖的方法,您可以在其中将 UIHostingController 子类化。

© www.soinside.com 2019 - 2024. All rights reserved.