【问题标题】:How to make an Xcode playground rotate to landscape如何使 Xcode 游乐场旋转到横向
【发布时间】:2018-02-27 11:22:52
【问题描述】:

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

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

当我在loadView() 中取消注释对simulateDeviceRotation(toOrientation:) 的调用时,结果是:

Rotation in loadView()

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

rotation in viewDidAppear(_:)

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

【问题讨论】:

    标签: swift swift-playground screen-rotation


    【解决方案1】:

    不要搞错方向,你不会成功的。

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

    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,一切都会好起来的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多