无法在 swift ui 中使用具有 if else 条件的切换开关
我无法访问使用交换机。我希望如果开关打开,它应该出现一个文本字段,如果开关关闭,变量的值应该为零。谁能帮我解决这个问题。我尝试过使用两种不同的方法。一种使用 .Onchange,另一种不使用 .Onchange。当我使用 .Onchange 时,它会出现一个问题,即文本字段的结果未使用。当我不使用 .onAppear 时,它不接受(userSettings.load = 0),但文本字段工作正常。我不明白我在这里做错了什么。变量定义为:
struct TwoView: View {
@EnvironmentObject var userSettings: UserSettings
@State var load: Bool = false
var body: some View {
NavigationView {
VStack {
Form {
Toggle("Casual loading", isOn: $load)
.onChange(of: load) { value in
if load == false
{
userSettings.loadrate = 0
}
else
{
TextField("Casual Loading", value: $userSettings.loadrate, format: .number)
}
}
}
}
}
}
}
class UserSettings: ObservableObject
{
@Published var loadrate = Float()
}
I am not able to access use the switch. I want if the switch is on, it should come up with a text field and if it is off the value of the variable should be zero. Can anyone help me with this. I have tried to use two different methods. One by using .Onchange and one without using .Onchange. When I use .Onchange, it comes up with a waning that the result of text field is unused. And when I don't use .onAppear it doesn't accept (userSettings.load = 0) but the text field works fine then. I don't understand what I am doing wrong here.The variables are defined as :
struct TwoView: View {
@EnvironmentObject var userSettings: UserSettings
@State var load: Bool = false
var body: some View {
NavigationView {
VStack {
Form {
Toggle("Casual loading", isOn: $load)
.onChange(of: load) { value in
if load == false
{
userSettings.loadrate = 0
}
else
{
TextField("Casual Loading", value: $userSettings.loadrate, format: .number)
}
}
}
}
}
}
}
class UserSettings: ObservableObject
{
@Published var loadrate = Float()
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
现在,您在视图层次结构之外、在
onChange
内部使用TextField
。事实上,正如您所提到的,Xcode 正在向您发出警告,告知您它未使用。要解决此问题,您可以在层次结构本身内使用
if
子句:Right now, you're using
TextField
outside of the view hierarchy, and just inside theonChange
. In fact, as you mentioned, Xcode is giving you a warning about the fact that it is unused.To solve this, you can use an
if
clause inside the hierarchy itself:TextField 是一个视图元素,它不应该位于闭包内。它应该是视图的子视图。
同样,赋值不是视图元素,因此不接受它出现在视图中。
因此,您需要做的是将
userSettings.loadrate = 0
放入.onChange
中,并将TextField
置于.onChange
之外代码>.我不确定您的预期结果到底是什么,但这是一个示例。
TextField is a view element and it shouldn't be inside a closure. It should be a child of a view.
Similarly, assignment is not a view element, so it is not accepted to be in a view.
So, what you need to do is put
userSettings.loadrate = 0
into.onChange
, and putTextField
outside.onChange
.I'm not sure what exactly is your expected result, but here is an example.