【问题标题】:How to change the Navigation View Style of a Navigation View depending on a @State in SwiftUI?如何根据 SwiftUI 中的 @State 更改导航视图的导航视图样式?
【发布时间】:2021-04-15 06:46:22
【问题描述】:

我目前在SwiftUI 中与Navigation View 合作。

问题:我想使用 @State & @BindingNavigation View StyleDescendent View 更改为。

@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())
}

显然,这不起作用,因为元素具有不同的类型。 错误消息: '?:' 表达式中的结果值具有不匹配的类型 'DefaultNavigationViewStyle' 和 'StackNavigationViewStyle'

问题:如何使用@State & @Binding 更改Navigation View Style而不创建一个完全不同的 NavigationView 并丢失所有 State

【问题讨论】:

    标签: swift swiftui navigation state navigationview


    【解决方案1】:

    您可以使用条件修饰符:

    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: { $0.navigationViewStyle(DefaultNavigationViewStyle()) },
        ifFalse: { $0.navigationViewStyle(StackNavigationViewStyle()) }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2020-12-23
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      相关资源
      最近更新 更多