我有一个视图控制器,希望它能有以下功能。在这个视图控制器中,我有一个按钮,当点击它时,强制将方向旋转到横向右侧。
在“部署信息 - 设备方向”中,我启用了“横向右侧”和“纵向”。
需要说明的是,在我的设备上,我启用了“纵向方向锁定”,因此我需要使用以下代码通过编程方式旋转方向。
let rotateButton: UIButton = {
let btn = UIButton(type: .system)
btn.setTitle("Rotate", for: .normal)
btn.setTitleColor(.red, for: .normal)
btn.addTarget(self, action: #selector(rotateTapped), for: .touchUpInside)
return btn
}()
@objc func rotateTapped() {
let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
因此,上述代码正常工作,屏幕正在旋转。
虽然我希望当用户回到纵向时,屏幕可以再次自动旋转到纵向,而无需按任何按钮。
当“锁定纵向方向”开启时,屏幕不会旋转回纵向。我尝试过以下代码,但没有成功。
1)
NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
@objc func rotated() {
if UIDevice.current.orientation.isLandscape {
print("Landscape") //when the user taps the button this is being printed.
} else {
print("Portrait") //when the user rotates back to portrait this is NOT being printed.
}
}
并且2)
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation == .landscapeRight {
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
}
当用户再次旋转手机时,有没有任何想法可以使其更改回纵向?