SwiftUI:如何在具有SidebarListStyle的NavigationView / List中选择NavigationLink

4
我希望能够通过编程在 NavigationView / List 中选择特定的 NavigationLink。以下代码在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横屏模式下会失效:虽然导航本身可用(目标显示正确),但导航链接仍未选中。
→ 如何选择导航链接以使其在iPad上也出现选中状态?
1个回答

6

这里是一种可能的方法。其思路是通过视图模型以编程方式激活导航链接,但将模型层级的选择和演示(由链接拥有)分开。

在 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
        })
    })
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接