【问题标题】:IPad Playground Has Different View.FrameiPad Playground 有不同的 View.Frame
【发布时间】:2019-03-19 03:52:28
【问题描述】:

我正在尝试使用以下代码在 iPad Playgrounds 中展示这个简单的 ViewController:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    setupViews()
}

func setupViews() {
    let view1 = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width/2, height: 100))
    view1.backgroundColor = .red
    view.addSubview(view1)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

您可以看到,即使它为 View1 的框架显示 view.frame.width/2,但视图仍然是这样的:

怎么了?谢谢。

【问题讨论】:

  • 如果你将半屏预览的边缘一直拖到左边——这样你就可以得到全屏预览——红色视图是否仍然覆盖了整个宽度?我怀疑问题在于MyViewController 实时视图太大而无法容纳预览,因此似乎裁剪为预览大小。
  • 有点奇怪,如果我把它一直拖出来,如果我把它一直拖出来,它会覆盖大约 60% 的宽度。

标签: swift xcode ipad swift-playground ipad-playgrounds


【解决方案1】:

这是我使用的解决方案。在 Swift Playgrounds 中,布局是在 viewDidLayoutSubview 方法中创建的,因此所有框架都应该在那里创建。

【讨论】:

    【解决方案2】:

    您可以在初始化 ViewController 后设置您喜欢的尺寸:

    import UIKit
    import PlaygroundSupport
    
    class VC: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            setupViews()
        }
    
        func setupViews() {
            let view1 = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width/2, height: 100))
            view1.backgroundColor = .red
            view.addSubview(view1)
        }
    }
    
    let vc = VC()
    vc.preferredContentSize = CGSize(width: 768, height: 1024)
    
    PlaygroundPage.current.liveView = vc
    

    Playground with preferredContentSize

    Playground without preferredContentSize

    【讨论】:

    • 对我不起作用。请记住,我在 iPad 上运行。感谢您的帮助!
    • @NikolasIoannou,这令人沮丧。我刚拿出我的 iPad 版本,看起来右边的预览没有做正确的事情(我想知道是否有办法让 liveView 全屏显示)。如果您点击addSubview(_:) 呼叫下方的小方块,它看起来应该正常工作i.stack.imgur.com/h8k3C.png
    • 是的,这很奇怪。我得调查一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2015-04-22
    相关资源
    最近更新 更多