marker johny
marker johny

Reputation: 91

sheet with function and button

I am new with swift and SwiftUI

Why .sheet not working with function ? When I try the below code, I get this error:

Ambiguous reference to member 'sheet(item:onDismiss:content:)'

Here is my code :

import SwiftUI

struct ContentView: View {

    @State var search = ""
    @State var show = false

    var body: some View {

        VStack {
            TextField("search", text: $search)
            Button("search") {
                self.show.toggle()
            }
            .sheet(isPresented: $show) {
                self.googlecom(D: self.search)
            }
        }
    }

    func googlecom(D: String) -> some View {
        guard let url = URL(string: "https://google.com/\(D)") else { return }
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
        return Text("")
    }

}

Upvotes: 3

Views: 362

Answers (2)

Jawad Ali
Jawad Ali

Reputation: 14417

You need to return a view

struct DetailView: View {
    var body: some View {
        Text("Detail")
    }
}

struct ContentView: View {

    @State var show = false

    var body: some View {

        VStack {
            Button("GO") {
                self.show.toggle()
            }

            .sheet(isPresented: $show) {
                DetailView()
            }
        }
    }


}

Upvotes: 0

Asperi
Asperi

Reputation: 258441

In SwiftUI almost everything requires or returns a View, so look carefully into interface declarations. Here is about sheet

/// Presents a sheet.
///
/// - Parameters:
///     - isPresented: A `Binding` to whether the sheet is presented.
///     - onDismiss: A closure executed when the sheet dismisses.
///     - content: A closure returning the content of the sheet.
public func sheet<Content>(isPresented: Binding<Bool>, onDismiss: (() -> Void)? = nil, 
              @ViewBuilder content: @escaping () -> Content) -> some View where Content : View

As it is seen content is ViewBuilder that should provide a View, so your function (if you want use function) code should look like

func openall() -> some View {
    print("Hello")
    return Text("Sheet content view is here")
}

Upvotes: 1

Related Questions