如何根据 SwiftUI 中的@State 更改导航视图的导航视图样式?
How to change the Navigation View Style of a Navigation View depending on a @State in SwiftUI?
我目前在 SwiftUI
与 Navigation View
一起工作。
问题: 我想使用 @State & @Binding
.
从 Descendent View
更改 Navigation View Style
@Binding var defaultNavigationStyle: Bool
var body: some View {
NavigationView {
sidebar
Text("Choose an Option from the Sidebar.")
Text("Select an Element.")
}
.navigationViewStyle(defaultNavigationStyle ? DefaultNavigationViewStyle() : StackNavigationViewStyle())
}
Obviously, this does not work since the Elements have different Types. Error Message: Result Values in '?:' expression have mismatching types 'DefaultNavigationViewStyle' and 'StackNavigationViewStyle'
问题:如何使用@State & @Binding
、而不创建完全不同的 NavigationView 来更改 Navigation View Style
并失去所有 State
?
您可以使用条件修饰符:
extension View {
typealias ContentTransform<Content: View> = (Self) -> Content
@ViewBuilder
func conditionalModifier<TrueContent: View, FalseContent: View>(
_ condition: Bool,
ifTrue: ContentTransform<TrueContent>,
ifFalse: ContentTransform<FalseContent>
) -> some View {
if condition {
ifTrue(self)
} else {
ifFalse(self)
}
}
}
并将其应用于 NavigationView
:
NavigationView {
sidebar
Text("Choose an Option from the Sidebar.")
Text("Select an Element.")
}
.conditionalModifier(
defaultNavigationStyle,
ifTrue: { [=11=].navigationViewStyle(DefaultNavigationViewStyle()) },
ifFalse: { [=11=].navigationViewStyle(StackNavigationViewStyle()) }
)
我目前在 SwiftUI
与 Navigation View
一起工作。
问题: 我想使用 @State & @Binding
.
Descendent View
更改 Navigation View Style
@Binding var defaultNavigationStyle: Bool
var body: some View {
NavigationView {
sidebar
Text("Choose an Option from the Sidebar.")
Text("Select an Element.")
}
.navigationViewStyle(defaultNavigationStyle ? DefaultNavigationViewStyle() : StackNavigationViewStyle())
}
Obviously, this does not work since the Elements have different Types. Error Message: Result Values in '?:' expression have mismatching types 'DefaultNavigationViewStyle' and 'StackNavigationViewStyle'
问题:如何使用@State & @Binding
、而不创建完全不同的 NavigationView 来更改 Navigation View Style
并失去所有 State
?
您可以使用条件修饰符:
extension View {
typealias ContentTransform<Content: View> = (Self) -> Content
@ViewBuilder
func conditionalModifier<TrueContent: View, FalseContent: View>(
_ condition: Bool,
ifTrue: ContentTransform<TrueContent>,
ifFalse: ContentTransform<FalseContent>
) -> some View {
if condition {
ifTrue(self)
} else {
ifFalse(self)
}
}
}
并将其应用于 NavigationView
:
NavigationView {
sidebar
Text("Choose an Option from the Sidebar.")
Text("Select an Element.")
}
.conditionalModifier(
defaultNavigationStyle,
ifTrue: { [=11=].navigationViewStyle(DefaultNavigationViewStyle()) },
ifFalse: { [=11=].navigationViewStyle(StackNavigationViewStyle()) }
)