gpt4 book ai didi

ios - 使用按钮以编程方式更改方向 - iOS

转载 作者:搜寻专家 更新时间:2023-10-30 22:36:57 25 4
gpt4 key购买 nike

我有一个 View Controller ,我想有以下体验。在 View Controller 内,我有一个按钮,它强制将方向旋转到右横向。

在 Deployment Info - Device Orientation 中我启用了“Landscape Right”和“Portrait”。

我想提一下,在我的设备中我启用了“纵向方向锁定”,这就是为什么我想要一个按钮来使用以下代码以编程方式旋转方向。

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。

objective-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 执行它。

关于ios - 使用按钮以编程方式更改方向 - iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50386875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com