在某些UI上支持方向更改但不是全部

时间:2017-03-25 02:59:51

标签: ios swift

我正在制作一个绘图应用程序,我希望用户能够旋转他们的设备并在画布上以任何方向绘制。画笔/颜色/等的工具栏需要改变方向以始终位于屏幕的顶部。但是绘图画布不需要改变方向(以便保留图形的方向;想象一下用一张图纸旋转一张纸) - 图纸有时会横向或颠倒,但你的铅笔仍然在你面前。)

我已经尝试了几次尝试,并得出结论我想支持iOS的默认方向更改,因为像UIAlert弹出窗口这样的东西需要正确定位。在视图控制器上实现override var supportedInterfaceOrientations: UIInterfaceOrientationMask不是最佳选择。

通过订阅device orientation changed notifications并在相反方向旋转绘图画布来补偿默认的UI方向旋转,我已经接近了。在这种情况下,我将CGAffineTransform旋转90度,-90度,0度或180度应用于画布容器视图,但其子视图无法正确旋转。

我可能缺少什么想法来获得我想要的行为?

这就是我想要的。请注意工具栏在旋转后始终如何朝向顶部,但绘图仍然粘在设备上。

在改变方向之前:

改变方向后:

1 个答案:

答案 0 :(得分:0)

我做了一个快速测试应用程序,看看你是否经历过(关于旋转画布视图而不是让其子视图旋转),我无法复制你所看到的内容。

我只是在主视图中的viewDidLoad上设置了一个观察者:

NotificationCenter.default.addObserver(self, selector:#selector(self.orientationChanged(_:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object:nil)

方向更改通知的处理方式如下:

func orientationChanged(_ n:Notification) {
    let orientation = UIDevice.current.orientation
    if orientation == UIDeviceOrientation.portrait {
        // No rotation
        vwCanvas.transform = CGAffineTransform(rotationAngle:0)
    } else if orientation == UIDeviceOrientation.portraitUpsideDown {
        // Rotate canvas 180 degrees
        vwCanvas.transform = CGAffineTransform(rotationAngle:CGFloat.pi)
    } else if orientation == UIDeviceOrientation.landscapeLeft {
        // Rotate canvas 90 degrees counterclockwise
        vwCanvas.transform = CGAffineTransform(rotationAngle:CGFloat.pi/2.0)
    } else if orientation == UIDeviceOrientation.landscapeRight {
        // Rotate canvas 90 degrees clockwise
        vwCanvas.transform = CGAffineTransform(rotationAngle:-CGFloat.pi/2.0)
    }
}

这是我的纵向屏幕:

enter image description here

以下是旋转版本: enter image description here

正如您所注意到的,子视图也在上面旋转。所以只是想知道我的版本和你的版本之间有什么区别(因为我不知道你的代码是什么样的),当你旋转画布时你没有旋转子视图......