使用button-iOS以编程方式更改方向
我有一个视图控制器,我想有以下经验。 在视图控制器内,我得到一个按钮,该按钮强制向右旋转方向 在部署信息-设备方向中,我启用了“横向右侧”和“纵向” 我想提到的是,在我的设备中,我已经启用了“纵向方向锁定”,这就是为什么我需要一个按钮来通过以下代码以编程方式旋转方向使用button-iOS以编程方式更改方向,ios,swift,swift3,orientation,ios11,Ios,Swift,Swift3,Orientation,Ios11,我有一个视图控制器,我想有以下经验。 在视图控制器内,我得到一个按钮,该按钮强制向右旋转方向 在部署信息-设备方向中,我启用了“横向右侧”和“纵向” 我想提到的是,在我的设备中,我已经启用了“纵向方向锁定”,这就是为什么我需要一个按钮来通过以下代码以编程方式旋转方向 let rotateButton: UIButton = { let btn = UIButton(type: .system) btn.setTitle("Rotate", for: .normal) bt
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")
}
因此,上面的代码工作正常,屏幕正在旋转。
虽然我希望当用户旋转回到纵向时,屏幕可以在不按下任何按钮的情况下再次旋转到纵向。
当“纵向方向锁定”打开时,屏幕不会旋转回纵向
我尝试了以下代码,但没有成功
(一)
(二)
你知道当用户再次旋转手机时,将其改回肖像会是什么吗?我没有swift代码。下面是
目标c
代码,它对我有效。您可以根据需要将其转换为swift
目标C
UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
[UIViewController attemptRotationToDeviceOrientation];
#更新
Swift 4.0
var value = UIInterfaceOrientation.landscapeRight.rawValue
if UIApplication.shared.statusBarOrientation == .landscapeLeft || UIApplication.shared.statusBarOrientation == .landscapeRight{
value = UIInterfaceOrientation.portrait.rawValue
}
UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()
上面的代码已经过我的测试,并且运行良好。如果上面的代码不适用于您,请使用
performSelector
在延迟一段时间后执行它。据我所知,上面的代码是当用户按下按钮(或w/e)并希望以编程方式将屏幕旋转到横向时执行的。对吗?iOS 13呢?我没有用iOS 13检查上面的代码。如果您发现任何问题,请让我知道。请通过解释代码的内容来改进您的答案。非常感谢。
var currentOrientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
var value = .landscapeRight
UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()
var value = UIInterfaceOrientation.landscapeRight.rawValue
if UIApplication.shared.statusBarOrientation == .landscapeLeft || UIApplication.shared.statusBarOrientation == .landscapeRight{
value = UIInterfaceOrientation.portrait.rawValue
}
UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()
var currentOrientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
var value = .landscapeRight
UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()