在 Swift 个游乐场更改实时取景画面

Change frame of Live View in Swift playgrounds

我不知道如何更改 Swift 游乐场中 Live View frame 的大小。这是我的代码:

public struct PlaygroundRootView: View {
    public var body: some View {
        Rectangle()
            .frame(width: 200, height: 100, alignment: .center)
            .foregroundColor(Color.blue.opacity(0.7))
            .cornerRadius(20)
     } 
} 
PlaygroundPage.current.liveView = UIHostingController(rootView: PlaygroundRootView())

我想让 Live View 变宽,改变它的大小。

您需要定义 UIHostingControllerpreferredContentSize,如:

import PlaygroundSupport
import SwiftUI

public struct PlaygroundRootView: View {
    public var body: some View {
        Rectangle()
            .frame(width: 200, height: 100, alignment: .center)
            .foregroundColor(Color.blue.opacity(0.7))
            .cornerRadius(20)
     }
}

let host = UIHostingController(rootView: PlaygroundRootView())
host.preferredContentSize = CGSize(width: 600, height: 600)
PlaygroundPage.current.liveView = host

Result