如何让Xcode游乐场旋转到风景

问题描述 投票:1回答:1

我正在尝试测试景观视图,但到目前为止我无法取得进展。我的代码看起来像这样:

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(_:)

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

swift swift-playground screen-rotation
1个回答
0
投票

不要乱用方向,你不会成功。

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

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

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

Update

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

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

print(myViewController.preferredContentSize)

宽度为375.0,高度为668.0。

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

© www.soinside.com 2019 - 2024. All rights reserved.