简体   繁体   English

如何在 SwiftUI 中使用带有绑定参数的可选 @State 变量

[英]How to use optional @State variable with binding parameter in SwiftUI

I am trying to use an optional @State variable with a TextField.我正在尝试将可选的@State变量与 TextField 一起使用。 This is my code:这是我的代码:

struct StorageView: View {
    
    @State private var storedValue: String?
    
    var body: some View {
        VStack {
            TextField("Type a value", text: $storedValue)
        }
        
    }
}

When I use this code, I get the following error: Cannot convert value of type 'Binding<String?>' to expected argument type 'Binding<String>'当我使用此代码时,出现以下错误: Cannot convert value of type 'Binding<String?>' to expected argument type 'Binding<String>'

I have tried the following code for both the values to be optional, but nothing seems to work:我已经尝试了以下代码来使这两个值都是可选的,但似乎没有任何效果:

TextField("Type a value", text: $storedValue ?? "")
TextField("Type a value", text: Binding($storedValue)!)

How would I go about using an optional @State variable with a binding?我 go 如何使用带有绑定的可选@State变量? Any help with this is appreciated.对此的任何帮助表示赞赏。

How would I go about using an optional @State variable with a binding?我 go 如何使用带有绑定的可选 @State 变量? Any help with this is appreciated.对此的任何帮助表示赞赏。

It looks like you are using an optional state variable with a binding.看起来您正在使用带有绑定的可选 state 变量。 You get an error because TextField 's initializer expects a Binding<String> rather than a Binding<String?> .您收到错误是因为TextField的初始化程序需要Binding<String>而不是Binding<String?> I guess you could solve the problem by adding another initializer that accepts Binding<String?> , or maybe making an adapter that converts between Binding<String?> and Binding<String> , but a better option might be to have a good think about why you need your state variable to be optional in the first place.我猜你可以通过添加另一个接受Binding<String?>的初始化程序来解决问题,或者制作一个在Binding<String?>Binding<String>之间转换的适配器,但更好的选择可能是好好考虑一下为什么你首先需要你的 state 变量是可选的。 After all this string something that will be displayed in your UI -- what do you expect your TextField to display if storedValue is nil?在所有这些字符串之后,将在您的 UI 中显示一些内容——如果storedValue为 nil,您希望您的TextField显示什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM