【问题标题】:Default selection in sidebar navigation侧边栏导航中的默认选择
【发布时间】:2021-05-16 20:05:02
【问题描述】:

我在 iOS/iPadOS 上构建了侧边栏导航,我想预先选择第一个侧边栏项以避免在启动时显示空白视图。

struct SidebarNavigation: View {
    enum Item: String, CaseIterable, Identifiable, Hashable {
        case inbox = "Inbox"
        case sent = "Sent"
        
        var id: String { rawValue }
        
        var destination: some View { Text(rawValue) }
    }
    
    @State var selection: Item? = .inbox
    
    var body: some View {
        NavigationView {
            List(selection: $selection) {
                ForEach(Item.allCases) { item in
                    NavigationLink(
                        destination: item.destination,
                        tag: item,
                        selection: $selection,
                        label: {
                            Text(item.rawValue)
                        })
                }
            }
            
            Text("Select Sidebar Item")
            
            Text("Detail View")
        }
    }
}

即使selection 设置为.inbox,在 iPad 上启动它也会出现以下情况。我还尝试在NavigationView 上使用onAppear 修饰符设置selection 属性,但是该代码仅在点击Back 按钮时才会执行,这会产生故障。有没有办法解决这个问题还是 SwiftUI 的限制?

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    您传递给NavigationView 的第二个视图是您要使用的目标视图。

    我用目标视图替换了第二个Text,它现在可以工作了。我还修改了目标视图,以表明这与 NavigationLink 标签不同。

    工作代码:

    struct SidebarNavigation: View {
        enum Item: String, CaseIterable, Identifiable, Hashable {
            case inbox = "Inbox"
            case sent = "Sent"
            
            var id: String { rawValue }
            
            var destination: some View {
                VStack {
                    Text(rawValue)
                    
                    Text("More content...")
                }
            }
        }
        
        @State var selection: Item? = .inbox
        @State private var tableView: UITableView?
        
        var body: some View {
            NavigationView {
                List(selection: $selection) {
                    ForEach(Item.allCases) { item in
                        NavigationLink(
                            destination: item.destination,
                            tag: item,
                            selection: $selection,
                            label: { Text(item.rawValue) }
                        )
                    }
                }
                
                if let selection = selection {
                    selection.destination
                }
                
                Text("Detail View")
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      • 2014-07-03
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      相关资源
      最近更新 更多