[英]SwiftUI is it possible to pass range of binding in ForEach?
我想在 ForEach 內的 model 中傳遞一個數組范圍。
我重新創建了一個示例:
import SwiftUI
class TheModel: ObservableObject {
@Published var list: [Int] = [1,2,3,4,5,6,7,8,9,10]
}
struct MainView: View {
@StateObject var model = TheModel()
var body: some View {
VStack {
ForEach (0...1, id:\.self) { item in
SubView(subList: $model.list[0..<5]) <-- error if I put a range
}
}
}
}
struct SubView: View {
@Binding var subList: [Int]
var body: some View {
HStack {
ForEach (subList, id:\.self) { item in
Text("\(item)")
}
}
}
}
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView()
}
}
周圍的工作
我發現是傳遞所有列表並執行 subView 內的范圍。 但我不想這樣做,因為數組非常大:
struct MainView: View {
@StateObject var model = TheModel()
var body: some View {
VStack {
ForEach (0...1, id:\.self) { i in
SubView(subList: $model.list, number: i, dimension: 5)
}
}
}
}
struct SubView: View {
@Binding var subList: [Int]
var number: Int
var dimension: Int
var body: some View {
HStack {
ForEach (subList[number*dimension..<dimension*(number+1)].indices, id:\.self) { idx in
Button(action: {
subList[idx] += 1
print(subList)
}, label: {
Text("num: \(subList[idx])")
})
}
}
}
}
我會將 model 傳遞給子視圖,因為它是 class 並將通過引用傳遞,然后將范圍作為單獨的參數傳遞。
這是我對 SubView 的新實現
struct SubView: View {
var model: TheModel
var range: Range<Int>
var body: some View {
HStack {
ForEach (model.list[range].indices, id:\.self) { idx in
HStack {
Button(action: {
model.list[idx] += 1
print(model.list)
}, label: {
Text("num: \(model.list[idx])")
})
}
}
}
}
}
請注意,我向ForEach
header 添加了indices
,以確保我們使用索引而不是數組中的值訪問數組。
調用視圖看起來像
var body: some View {
VStack {
SubView(model: model, range: (0..<5))
Text("\(model.list.map(String.init).joined(separator: "-"))")
}
額外的Text
僅用於測試目的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.