Xcode 12.4/Swift Playgrounds:代码不生成视图

问题描述

我是 Xcode 12.4/Playgrounds 的新手,正在尝试运行此代码。到目前为止,它不会生成 View 对象,也不会生成错误代码。对我做错了什么有任何想法吗?

import SwiftUI
import PlaygroundSupport

struct ExampleView: View{
    var body: some View {
        vstack {
            Rectangle()
                .fill(Color.blue)
                .frame(width:200,height:200)
            Button(action: {
                })
            Text("Rotate")
        }
    };.padding(10)
}

PlaygroundPage.current.setLiveView(Example-View())
    .padding(100)

解决方法

Playgrounds 仍然有点问题(已经很多年了)...无论如何,您有几个错误:

Errors highlighted in code

  • Missing argument for parameter #1 in call:您在 {} 之后缺少括号 Button 来定义它的外观
  • Expected declaration:像 .padding() 这样的修饰符需要在 var body: some View 内。将其移到 VStack 之后的右侧。
  • Cannot find 'Example' in scope:你拼错了 ExampleView
  • 目前还没有错误,但您也无法将 .padding() 附加到 PlaygroundPage.current.setLiveView(ExampleView())。修饰符始终需要位于 View 内。

这是固定代码:

import SwiftUI
import PlaygroundSupport

struct ExampleView: View {
    var body: some View {
        VStack {
            Rectangle()
                .fill(Color.blue)
                .frame(width: 200,height: 200)

            Button(action: {
                
            }) {
                Text("Rotate")
            }
        }
        .padding(10)
    }
}

PlaygroundPage.current.setLiveView(ExampleView())

结果:

Error-free code on left,blue square with button underneath in the live view on right