如何以编程方式更改设备方向,屏幕的旋转方向应按顺时针方向

时间:2018-04-30 12:39:20

标签: ios objective-c orientation

我想点击按钮强行旋转屏幕。我有两个按钮,一个用于在顺时针方向中旋转屏幕,另一个用于在反时钟方向中旋转。

我的代码是 - 1)[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft] forKey:@"orientation"] 对于反时钟旋转和它的工作正常。

2)[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIDeviceOrientationLandscapeRight] forKey:@"orientation"] 用于顺时针旋转。此代码还以反时钟方向旋转屏幕。我除了时钟方向旋转外。

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

iOS中的每个方向都有原始值。

  1. portrait = 1
  2. portraitUpsideDown = 2
  3. landscapeLeft = 3
  4. landscapeRight = 4
  5. 您可以根据这些值更改方向。

    以下是我在 swift

    中的表现
    1. 顺时针旋转:

      @IBAction func rotateClockwise(_ sender: Any) {
      
      
      let orientation = UIDevice.current.orientation
      print("Current state:",orientation.rawValue)
      var newOrientation: Int {
          switch orientation.rawValue {
          case 1:
              return 3
          case 2:
              return 4
          case 3:
              return 2
          case 4:
              return 1
          default:
              return 1
          }
      }
      
      
      UIDevice.current.setValue(newOrientation, forKey: "orientation")
      

      }

    2. 逆时针方向旋转:

      @IBAction func rotateAntiClockwise(_ sender: Any) {
      
      let orientation = UIDevice.current.orientation
      print("Current state:",orientation.rawValue)
      var newOrientation: Int {
          switch orientation.rawValue {
          case 1:
              return 4
          case 2:
              return 3
          case 3:
              return 1
          case 4:
              return 2
          default:
              return 1
          }
      }
      
      
      UIDevice.current.setValue(newOrientation, forKey: "orientation")
      }
      
    3. 注意

      确保在目标中选择all orientations - 一般

      如果不起作用,请添加以下代码以查看控制器类

      override var supportedInterfaceOrientations: UIInterfaceOrientationMask { get { return .all } }