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

标签 ios swift swift3 orientation ios11

我有一个 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/

相关文章:

ios - App Delegate - 快速加载核心数据

ios - 在 Swift 中将城市名称转换为坐标

ios - 如何将通用字符名称转换为其在 objective-c 中的实际值?

swift - 将 Swift 用于 Mac 应用程序的优缺点是什么?

ios - contentOffset 反方向计算

ios - 如何使用 swift3 在​​ UITableView 的两个不同单元格中显示两个数组

ios - 检查后尝试使用现有主键创建对象的 RLMException

swift - 在 Swift 中访问枚举关联值

ios - 仅检测矩形物理体一侧的碰撞 - Swift3

swift - 我如何重写此 switch 语句以便以特定方式对字符串数组进行排序