首页 > 解决方案 > Xcode Playground 上的 SwiftUI 与 Swift Playground - 不同的输出

问题描述

我在 Xcode Playground 和 Swift Playground 上运行这段代码:

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    var body: some View {
        VStack{
            ZStack {
                Color.white
                Text("hello World")
                    .foregroundColor(.black)
                
            }
            .edgesIgnoringSafeArea(.vertical)
            Circle()
                .foregroundColor(.blue)
        }
    }
}

PlaygroundPage.current.setLiveView(ContentView())

有人知道为什么我们从相同的代码中得到如此不同的输出吗?

Swift Playground 结果

Xcode 游乐场结果

标签: swiftxcodeswiftui

解决方案


在 iPad 上,您在黑暗模式下运行,这会使视图的默认背景变为黑色。此外,iPad Swift Playgrounds 提供了一个运行视图的框架。如果您在纵向和横向模式之间切换,此框架会有所不同,但在任何一种情况下,它都会提供一个用于绘制的框架。

在 Xcode 的 Playgrounds 中,视图只占用最小的大小。

.frame您可以通过提供和使用Color.black背景在 Xcode 中获得类似的外观:

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    var body: some View {
        VStack{
            ZStack {
                Color.white
                Text("hello World")
                    .foregroundColor(.black)
                
            }
            .edgesIgnoringSafeArea(.vertical)
            Circle()
                .foregroundColor(.blue)
        }
        .frame(width: 500, height: 600)
        .background(Color.black)
    }
}

PlaygroundPage.current.setLiveView(ContentView())

推荐阅读