gpt4 book ai didi

list - SwiftUI,以编程方式选择列表中的一行

转载 作者:行者123 更新时间:2023-12-03 16:35:16 26 4
gpt4 key购买 nike

我想以编程方式在 List 中设置选定的行。
在我下面的示例中,通过 2 个按钮。

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

试图使列表可以像这样选择:
List(selection: $selection)  

不编译。
编译器提示: Unable to infer complex closure return type; add explicit type to disambiguate

最佳答案

选择类型必须是可选的。找到下面的固定代码。

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

关于list - SwiftUI,以编程方式选择列表中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61838352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com