我有一个视图控制器,我希望有以下经验。在视图控制器内部,我有一个按钮,该按钮强制将方向旋转到正确的横向。
在“部署信息-设备方向”中,我启用了“横向右”和“纵向”。
我想提到的是,我在设备中启用了“纵向方向锁定”,这就是为什么我希望按钮使用以下代码以编程方式旋转方向。
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")
}
}
当用户再次旋转手机时又回到纵向,有什么想法吗?
我没有快速代码。下面是objective c
代码,它为我工作。您可以根据需要将其转换为swift。
射影C
UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
[UIViewController attemptRotationToDeviceOrientation];
迅捷4.0
var value : Int = 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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句