带有功能和按钮的工作表

时间:2019-12-30 04:18:06

标签: swift swiftui

我是swift和SwiftUI的新手

为什么.sheet无法使用功能?当我尝试以下代码时,出现此错误:

  

成员'sheet(item:onDismiss:content :)'的歧义引用

这是我的代码:

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

}

2 个答案:

答案 0 :(得分:0)

SwiftUI中,几乎所有内容都需要或返回View,因此请仔细查看接口声明。这是关于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

可以看到ViewBuilder的内容应该提供View,所以您的函数(如果要使用函数)代码应类似于

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

答案 1 :(得分:0)

您需要返回视图

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


}