[英]Clean view controller dismissal on iPhone & iPad
我有一個用於編輯對象細節的UIViewController
子類,它被推送到 iPhone 上的UINavigationController
上。
在 iPad 上,它是UINavigationController
的根視圖控制器,以UIModalPresentationPopover
的presentationStyle
。 換句話說,演示是在 iPhone 上推送,在 iPad 上是模態/彈出窗口。
所以演示在代碼中是這樣完成的:
蘋果手機:
self.navigationController.pushViewController(detailVC, animated: true)
iPad:
let nc = UINavigationController(rootViewController: detailVC)
nc.modalPresentationStyle = .popover
self.present(nc, animated: true)
我正在重新審視取消這個視圖控制器的代碼; 它需要在 iPhone 上彈出導航堆棧或在 iPad 上關閉彈出框。
目前代碼如下:
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.phone {
self.navigationController?.popViewController(animated: true)
} else {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
但讓我吃驚的是,幾乎可以肯定有一個更簡潔的解決方案——可能是 API 調用,它在兩個平台上都做正確的事情,對於兩種上下文,而不必根據設備習語來切換行為。
是否有更干凈/非特定於設備/更慣用的方法來處理 iPhone 和 iPad 上的此視圖控制器的關閉?
我希望並期待self.presentingViewController?.dismiss()
對這兩種情況都適用,但事實並非如此。
我很欣賞演示代碼可能需要適應最正確的演示和解雇方法。
我無法猜測以下是否是更簡潔的方法,但不是特定於設備的,我打算提供其他方法來做到這一點
將 UIViewController 呈現為 UINavigationController 的 rootVC 時,您可以檢查解除操作
if self.navigationController?.viewControllers.first === self {
dismiss(animated: true, completion: nil)
} else {
self.navigationController?.popViewController(animated: true)
}
或者,您可以對兩種情況進行 2 個操作
@objc func popAction() {
self.navigationController?.popViewController(animated: true)
}
@objc func dismissAction() {
dismiss(animated: true, completion: nil)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.