3

我带着另一个问题回来了。我正在关注本指南:https ://medium.com/@fs.dolphin/passing-data-between-views-in-swiftui-793817bba7b1

一切正常,但 SecondView_Previews 抛出错误Missing argument for parameter 'message' in call。这是我的 ContentView 和 SecondView

// ContentView
import SwiftUI

struct ContentView: View {
    @State private var showSecondView = false
    @State var message = "Hello from ContentView"
    
    var body: some View {
        VStack {
            Button(action: {
                self.showSecondView.toggle()
            }){
               Text("Go to Second View")
            }.sheet(isPresented: $showSecondView){
                SecondView(message: self.message)
        }
            Button(action: {
                self.message = "hi"
            }) {
                Text("click me")
            }
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
import SwiftUI

struct SecondView: View {
    @State var message: String
    
    var body: some View {
        Text("\(message)")
    }
}
 struct SecondView_Previews: PreviewProvider {
    static var previews: some View {
        SecondView() // Error here: Missing argument for parameter 'message' in call.
    }
 }

它尝试将其更改为 SecondView(message: String) 并将错误更改为“无法将'String.Type'类型的值转换为预期的参数类型'String'”

有人可以解释我做错了什么,或者如何正确设置预览。没有预览时一切正常。提前致谢!

4

1 回答 1

2
struct ContentView: View {
    @State var message: String //Define type here 
        var body: some View {
            Text("\(message)")
        }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(message: "Some text") //Passing value here 
    }
}
于 2020-12-07T20:29:07.450 回答