当它从一个ViewController推到另一个View Controller时,我想更改View的方向。就像按下时一样,应该将其变成人像才能变成风景。
我尝试使用此代码,但无法正常工作。
在ViewDidLoad
struct AppUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
在ViewController
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.landscapeRight, andRotateTo: UIInterfaceOrientation.landscapeRight)
}
但是它不会改变其方向。
答案 0 :(得分:0)
在应用程序委托中
import UIKit
let appDelegate = UIApplication.shared.delegate as! AppDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var deviceOrientation = UIInterfaceOrientationMask.portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return deviceOrientation
}
}
在UIViewController中
override func viewWillAppear(_ animated: Bool) {
appDelegate.deviceOrientation = .landscapeLeft
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
答案 1 :(得分:0)
我已经实现了相同的代码并遇到了相同的问题,因此我在调用“ lockOrientation”并解决它之前添加了以下代码。
UIDevice.current.setValue(UIInterfaceOrientationMask.landscapeRight.rawValue, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()