如何让Xcode游乐场旋转到横向

时间:2018-02-27 11:22:53

标签: swift swift-playground screen-rotation

我正在尝试测试景观视图,但到目前为止我无法取得进展。我的代码如下所示:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

  override func loadView() {

    let view = UIView()
    view.backgroundColor = .white
    let label = UILabel()
    label.text = "Hallo"
    label.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(label)
    self.view = view
    NSLayoutConstraint.activate([label.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
                                 label.centerXAnchor.constraint(equalTo: view.centerXAnchor)])
    simulateDeviceRotation(toOrientation: .landscapeLeft)
 }

  override func viewDidAppear(_ animated: Bool) {

    //simulateDeviceRotation(toOrientation: .landscapeLeft)

  }
}
// Present the view controller in the Live View window
func simulateDeviceRotation(toOrientation orientation: UIDeviceOrientation) {
  let orientationValue = NSNumber(value: orientation.rawValue)
  UIDevice.current.setValue(orientationValue, forKey: "orientation")
}

PlaygroundPage.current.liveView = MyViewController()

当我取消注释simulateDeviceRotation(toOrientation:)loadView()的来电时,结果为:

Rotation in loadView()

而且,当我在simulateDeviceRotation(toOrientation:)中取消注释viewDidAppear(_:)时,结果为:

rotation in viewDidAppear(_:)

当然,我希望看到第二个结果,但第一个是水平旋转。你能指点我正确的方向吗?我错过了一些东西,但我无法找到它。

1 个答案:

答案 0 :(得分:0)

不要弄乱方向,你就不会成功。

将代码的最后一行更改为:

var myViewController = MyViewController()
myViewController.preferredContentSize = CGSize(width: 668, height: 375)
PlaygroundPage.current.liveView = myViewController

并删除loadViewviewDidAppear中设备方向处理的所有内容,并删除方法simulateDeviceRotation

更新

如果您将任意值设置为preferredContentSize,则会遇到约束问题或更糟糕的情况,例如视图在实时视图中移位。

我做了什么:首先阅读当前内容大小的默认值:

print(myViewController.preferredContentSize)

宽度为375.0,高度为668.0。

所以只需将这个值换成新的preferredContentSize,一切都应该没问题。