首页 > 解决方案 > SwiftUI Function 声明一个 Opaque 返回类型,在一个 View 中插入两个按钮?

问题描述

我想构建一个简单的 SwiftUI ContentView.swift。在此应用程序的视图窗格中,它将包含两个按钮,其中隐含了它们的图像。我想过为每个按钮一个一个添加一个功能,然后让 SwiftUI 显示每个元素。我已经查看了一些与返回类型相关的问题,尽管如果我只有一个 Button(),我会在哪里添加返回类型让我感到困惑。我的代码很短,在我没有包含返回的地方很容易看出我哪里出错了?

struct ContentView: View {
    var body : some View {
        func Button1(){
        Button(action: {
         print("Here is a bit of information.")
        }) {
            Image(systemName: "info")
                .padding()
                .background(Color.green)
                .font(.largeTitle)
                .foregroundColor(Color.orange)
                .frame(width: 300, height: 600)
        }
        }
        func Button2(){
        Button(action: {
            print("You have erased it.")
        }) {
            Image(systemName: "trash")
            .padding()
                .background(Color.red)
                .font(.largeTitle)
                .foregroundColor(Color.white)
                .frame(width: 426, height: 620)
        }
        }
            }

我希望这两个按钮会出现在屏幕的第一个视图上,然后我可以在我了解代码中的位置后编辑它们将采取的动作。感谢您的见解 :)

标签: swiftreturnswiftui

解决方案


以下是您将如何执行此操作:

struct ContentView: View {
    var body: some View {
        VStack {
            Button(action: {
                print("Here is a bit of information.")
            }) {
                Image(systemName: "info")
                    .padding()
                    .background(Color.green)
                    .font(.largeTitle)
                    .foregroundColor(Color.orange)
                    .frame(width: 300, height: 600)
            }
            Button(action: {
                print("You have erased it.")
            }) {
                Image(systemName: "trash")
                    .padding()
                    .background(Color.red)
                    .font(.largeTitle)
                    .foregroundColor(Color.white)
                    .frame(width: 426, height: 620)
            }
        }
    }
}

推荐阅读