SwiftUI,以编程方式在列表中选择一行 [英] SwiftUI, selecting a row in a List programmatically
本文介绍了SwiftUI,以编程方式在列表中选择一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以编程方式设置列表中的选定行.
在下面的示例中,通过2个按钮.
I want to set the selected row in a List programmatically.
In my example below via 2 Buttons.
struct ContentView: View {
@State private var selection = 2
var body: some View {
VStack {
List() {
//List(selection: $selection) {. // does not compile
Text("Line 0").tag(1)
Text("Line 1").tag(1)
Text("Line 2").tag(2)
Text("Line 3").tag(3)
Text("Line 4").tag(4)
Text("Line 5").tag(5)
}
.listStyle(SidebarListStyle())
Text("Selected Item :\(self.selection)")
HStack {
Button(action: {if (self.selection < 5 ) { self.selection += 1 }} ) {Text("⬇︎")}
Button(action: {if (self.selection > 0 ) { self.selection -= 1 }} ) {Text("⬆︎")}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
试图使列表像这样可选:
trying to make the List selectable like this:
List(selection: $selection)
无法编译.
编译器抱怨:无法推断复杂的闭包返回类型;添加显式类型以消除歧义
推荐答案
选择类型必须是可选的.查找下面的固定代码.
Selection type must be optional. Find below fixed code.
struct TestListSelectionOnAction: View {
@State private var selection: Int? = 2 // optional !!
var body: some View {
VStack {
List(selection: $selection) {
Text("Line 0").tag(0)
Text("Line 1").tag(1)
Text("Line 2").tag(2)
Text("Line 3").tag(3)
Text("Line 4").tag(4)
Text("Line 5").tag(5)
}
.listStyle(SidebarListStyle())
Text("Selected Item :\(self.selection ?? -1)")
HStack {
Button(action: {
if (self.selection! < 5 ) { self.selection! += 1 }} ) {Text("⬇︎")}
Button(action: {
if (self.selection! > 0 ) { self.selection! -= 1 }} ) {Text("⬆︎")}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
这篇关于SwiftUI,以编程方式在列表中选择一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文