Swift Playground 中的 SwiftUI 预览大小看起来不正确

ale*_*enm 2 xcode swift swiftui

问题

我有这个基本的样板格式,可以在操场上尝试 Swiftui。预览实时视图始终是这个小矩形。我不知道这是 Swift Playgrounds 中的一个错误还是我错过了其他东西?(见图)

代码

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}

PlaygroundPage.current.setLiveView(ContentView())

Run Code Online (Sandbox Code Playgroud)

截屏

在此输入图像描述

更新的代码/屏幕截图

有人建议我提供UIHostingController并设置preferredContentSize. 所以我尝试了一下,但没有改变。同样的问题。请参阅下面的屏幕截图。

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}

let contentView = ContentView()
let hostingViewController = UIHostingController(rootView: contentView)
hostingViewController.preferredContentSize = CGSize(width: 700, height: 800)

PlaygroundPage.current.setLiveView(hostingViewController)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 6

使用原始代码时,您可以将.frame修饰符与 ContentView() 一起使用。您必须提供宽度和高度,当选择足够大的这些值时,您的视图应该更具吸引力。添加修改后您的代码可能如下所示:

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}

PlaygroundPage.current.setLiveView(
    ContentView()
        .frame(width: 500.0, height: 500.0)
        //provide a width and hight of your choice
)
Run Code Online (Sandbox Code Playgroud)

运行代码时将提供以下预览: Xcode Playground 中的代码提供的预览。