3

我刚刚偶然发现了这个问题,想知道是否有人可以帮助解释这个问题。

在 iPad 上使用时,我的视图有一个嵌套UINavigationController显示在弹出框内。我最近一直在将此代码转换为 Swift 并尝试使用延迟初始化,如下所示:

lazy var secondaryNavigationController: UINavigationController = {
    let navController = UINavigationController(rootViewController: menuView)
    navController.modalPresentationStyle = .popover
    navController.popoverPresentationController?.barButtonItem = menuButton
    return navController
}()

注意 menuView 和 menuButton 也是延迟初始化的

然后,我尝试将视图呈现如下:

@objc private func openMenu() {
    if UIDevice.current.userInterfaceIdiom == .pad {
        present(secondaryNavigationController, animated: true, completion: nil)
    } else {
        navigationController?.pushViewController(menuView, animated: true)
    }
}

我第一次打开菜单时一切正常,菜单按预期显示。但是,如果我通过点击屏幕的另一个区域来关闭菜单,然后再次尝试重新打开它,则会出现以下崩溃:

UIPopoverPresentationController () 应该在演示发生之前设置一个非零的 sourceView 或 barButtonItem。

openMenu()如果我对函数进行以下更改,此崩溃就会消失:

@objc private func openMenu() {
    if UIDevice.current.userInterfaceIdiom == .pad {
        secondaryNavigationController.popoverPresentationController?.barButtonItem = menuButton // hurrah!
        present(secondaryNavigationController, animated: true, completion: nil)
    } else {
        navigationController?.pushViewController(menuView, animated: true)
    }
}

那么上面的修复是必要的吗?我是否遗漏了任何可以在惰性初始化块中设置的明显内容?


(来自示例项目的崩溃日志)

2018-06-29 21:13:09.836061+0100 PopoverBugExample[90568:1465443] * 由于未捕获的异常“NSGenericException”而终止应用程序,原因:“UIPopoverPresentationController () 应该在演示发生之前设置非零 sourceView 或 barButtonItem。 ' *第一次抛出调用堆栈:(0 CoreFoundation 0x0000000110c4b7f6 exceptionPreprocess + 294 1 libobjc.A.dylib
0x000000010f2a3035 objc_exception_throw + 48 2 UIKitCore
0x0000000113323a0e -[UIPopoverPresentationController 6183 UIKitCore PresentationTransitionWillBegin] + 3
0x000000011332d568 __71-[UIPresentationController _initViewHierarchyForPresentationSuperview:]_block_invoke + 2495 4 UIKitCore 0x000000011332ab5c __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 468 5 UIKitCore
0x0000000112fd8965 _runAfterCACommitDeferredBlocks + 318 6
UIKitCore 0x0000000112fc77d3 _cleanUpAfterCAFlushAndRunDeferredBlocks + 397 7 UIKitCore 0x0000000112ff7131 _afterCACommitHandler + 141 8 CoreFoundation
0x0000000110baee97 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION
+ 23 9 CoreFoundation 0x0000000110ba92ce __CFRunLoopDoObservers + 430 10 CoreFoundation 0x0000000110ba9971 __CFRunLoopRun + 1553 11 CoreFoundation
0x0000000110ba9021 CFRunLoopRunSpecific + 625 12 GraphicsServices
0x000000011825c16e GSEventRunModal + 62 13 UIKitCore
0x0000000112fcd3ff UIApplicationMain + 140 14 PopoverBugExample
0x000000010e97c857 main + 71 15 libdyld.dylib
0x00000001120dce61 start + 1 16 ???
0x0000000000000001 0x0 + 1 ) libc++abi.dylib:以 NSException 类型的未捕获异常终止

4

0 回答 0