Search code examples
swiftreturnswiftui

SwiftUI Function declares an Opaque return type, inserting two buttons in one View?


I would like to build a simple SwiftUI ContentView.swift. In this App's view pane it would contain two buttons with their images implied. I thought about adding a function for each button one by one, then allowing SwiftUI to show each element. I have viewed some questions related to the return type, although it is confusing me as to where you would add a return type if I only have a Button(). My code is very short, is it easy to see where I went wrong where I did not include the return?

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)
        }
        }
            }

I am hoping that these two buttons will appear on the screen's first view, and I may then edit the action's they will both take after I understand the placement within the code. Thank you for your insight :)


Solution

  • Here's how you would do this:

    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)
                }
            }
        }
    }