[英]Change the device orientation from portrait to landscape on a button click in iOS
我一直在嘗試更改按鈕單擊事件的設備方向 2 天,但我無法正確實現它。
所以,我有一個最低版本為 12.4 的 iPhone 應用程序,而我用來測試的設備是 14.4。 我在這里使用了這個項目中提到的代碼(當使用 push 或 present 呈現新視圖 controller 時它可以正常工作)但是在同一個視圖 controller 上同樣不起作用。 用戶需要旋轉他/她的設備來啟動方向改變。
這是我試圖在按鈕單擊事件上旋轉的視圖 controller 中的代碼。
let appDelegate = AppDelegate.sharedInstance
let oldOrientaion = appDelegate.deviceOrientation
appDelegate.deviceOrientation = oldOrientaion == .landscapeRight ? .portrait : .landscapeRight
let value = appDelegate.deviceOrientation.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
有人可以幫我弄清楚這到底缺少什么嗎?
此外,在旁注中,視圖 controller 呈現在不同的視圖 controller 上,所以即使我嘗試呈現新視圖 controller 也不會像在項目中那樣改變方向一段時間。
編輯:
現在已修復。 我試圖使用UIInterfaceOrientationMask
UIInterfaceOrientation
設置方向。 因此,將代碼更改為最后使用UIInterfaceOrientation
現在可以正常工作。
謝謝您的幫助。
你做的一切都是正確的,只需要調用attemptRotationToDeviceOrientation
到設備方向的方法來使更改生效。 根據文檔:
一些視圖控制器可能希望使用特定於應用程序的條件來確定支持哪些界面方向。 如果您的視圖 controller 執行此操作,則當這些條件發生變化時,您的應用程序應調用此 class 方法。 系統立即嘗試旋轉到新方向。
在您的代碼中,它將如下所示:
UIViewController.attemptRotationToDeviceOrientation()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.