SwiftUI:在导航视图/带有SidebarListStyle的列表中选择NavigationLink

时间:2020-08-03 12:00:03

标签: swiftui navigationview navigationlink sidebarliststyle

我想以编程方式在NavigationLink / NavigationView中选择特定的List

下面的代码在纵向或横向模式==的iPhone上都可以正常使用,在这种情况下,除了目标视图之外,列表还不能永久可见。

enter image description here

代码:

struct ContentView: View {

private let listItems = [ListItem(), ListItem(), ListItem()]
@State var selection: Int? = 0

var body: some View {
    NavigationView {
        
        List(listItems.indices) {
            index in
            
            let item = listItems[index]
            let isSelected = (selection ?? -1) == index
            
            NavigationLink(destination: Text("Destination \(index)"),
                           tag: index,
                           selection: $selection) {
                
                Text("\(item.name) \(index) \(isSelected ? "selected" : "")")
                
            }
            
        }
    
    }
    .listStyle(SidebarListStyle())
    .onAppear(perform: {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
            selection = 2
        })
    })
    }

}


struct ListItem: Identifiable {
    var id = UUID()
    var name: String = "Some Item"
}

但是在横向模式下的iPad上却失败:导航本身可以正常工作(目的地显示正确), NavigationLink仍然未被选择。

→如何以在iPad上显示的方式选择NavigationLink?

1 个答案:

答案 0 :(得分:1)

这是可行的方法。这个想法是通过视图模型以编程方式激活导航链接,但是将模型级别的选择和表示(链接所拥有的)分开进行。

通过Xcode 12b3 / iOS + iPadOS 14测试。

class SelectionViewModel: ObservableObject {
    var currentRow: Int = -1 {
        didSet {
            self.selection = currentRow
        }
    }

    @Published var selection: Int? = nil
}

struct SidebarContentView: View {
@StateObject var vm = SelectionViewModel()
private let listItems = [ListItem(), ListItem(), ListItem()]

var body: some View {
    NavigationView {

        List(listItems.indices) {
            index in

            let item = listItems[index]
            let isSelected = vm.currentRow == index

            Button("\(item.name) \(index) \(isSelected ? "selected" : "")") { vm.currentRow = index }
            .background (
                NavigationLink(destination: Text("Destination \(index) selected: \(vm.currentRow)"),
                               tag: index,
                               selection: $vm.selection) {
                    EmptyView()
                }.hidden()
            )
        }

    }
    .listStyle(SidebarListStyle())
    .onAppear(perform: {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
            vm.currentRow = 2
        })
    })
    }
}