在 SwiftUI 中动态隐藏视图 [英] Dynamically hiding view in SwiftUI
问题描述
我正在尝试在 SwiftUI 中有条件地隐藏 DatePicker
.但是,我对不匹配的类型有任何问题:
I'm trying to conditionally hide a DatePicker
in SwiftUI. However, I'm having any issue with mismatched types:
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
在这种情况下,datePicker
是 DatePicker
类型,但 datePicker.hidden()
是 _ModifiedContent
.所以我不能将 datePicker.hidden()
分配给 datePicker
.我已经尝试过这种变体,但似乎无法找到一种有效的方法.有什么想法吗?
In this case, datePicker
is a DatePicker<EmptyView>
type but datePicker.hidden()
is a _ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>
. So I cannot assign datePicker.hidden()
to datePicker
. I've tried variations of this and can't seem to find a way that works. Any ideas?
更新
您可以解开 _ModifiedContent
类型以使用其 content
属性获取基础类型.但是,这并不能解决根本问题.content
属性似乎只是原始的、未修改的日期选择器.
You can unwrap the _ModifiedContent
type to get the underlying type using it's content
property. However, this doesn't solve the underlying issue. The content
property appears to just be the original, unmodified date picker.
推荐答案
我发现我可以通过这种方式隐藏或显示日期选择器,而不是动态设置变量并在我的视图中使用它:
Rather than dynamically setting a variable and using it in my view, I found that I was able to hide or show the date picker this way:
struct ContentView : View {
@State var showDatePicker = true
@State var datePickerDate: Date = Date()
var body: some View {
VStack {
if self.showDatePicker {
DatePicker($datePickerDate)
} else {
DatePicker($datePickerDate).hidden()
}
}
}
}
或者,可选地,不包括日期选择器而不是隐藏它:
Or, optionally, not including the date picker instead of hiding it:
struct ContentView : View {
@State var showDatePicker = true
@State var datePickerDate: Date = Date()
var body: some View {
VStack {
if self.showDatePicker {
DatePicker($datePickerDate)
}
}
}
}
这篇关于在 SwiftUI 中动态隐藏视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!