如何为按钮创建一个函数来打印控制台中文本字段中键入的数据

发布于 2025-01-14 23:04:51 字数 324 浏览 3 评论 0原文

struct ContentView: View {

@State private var name : String = ""

var body: some View {
    NavigationView{
        Form{
       
            Button(action: {
                print(Textfield)
            }) {
                Text("Salvar")
            }

我需要打印在 Textfield 中输入的结果。

struct ContentView: View {

@State private var name : String = ""

var body: some View {
    NavigationView{
        Form{
       
            Button(action: {
                print(Textfield)
            }) {
                Text("Salvar")
            }

I need to print the result typed at Textfield.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾铮苏瑾 2025-01-21 23:04:51

您混淆了视图 TextField,它允许您使用存储输入结果的变量输入文本。您无法打印您键入的视图,但可以打印变量的值。所以:

struct ContentView: View {
    // name holds the value
    @State private var name : String = ""
    
    var body: some View {
        NavigationView{
            Form{
                // TextField lets you change the value
                TextField("Name", text: $name)
                Button(action: {
                    // prints the value to the console
                    print(name)
                }) {
                    Text("Salvar")
                }
            }
        }
    }
}

You are confusing the view, TextField, which allows you to input text with the variable which stores the result of the input. You can't print the view into which you type, but you can print the value of the variable. Therefore:

struct ContentView: View {
    // name holds the value
    @State private var name : String = ""
    
    var body: some View {
        NavigationView{
            Form{
                // TextField lets you change the value
                TextField("Name", text: $name)
                Button(action: {
                    // prints the value to the console
                    print(name)
                }) {
                    Text("Salvar")
                }
            }
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文