我使用 disclousreGroup 作为递归,但视图更新无法正常工作。有什么办法吗?



输入图片描述

如果您在折叠后更改数据,视图将被重用并以奇怪的方式绘制。

在swiftUI中重用View似乎会产生这些结果。

我可以控制视图的重用吗?还是有别的办法?

与id有关吗?

代码如下:

import SwiftUI
@main
struct TestApp: App {
var item: Item = dummyItems
var item2: Item = dummyItems2
@State var isChange: Bool = true

var body: some Scene {
WindowGroup {
VStack {
List {
if isChange {
ContentView(item: item)
} else {
ContentView(item: item2)
}
}
Button("change") {
isChange.toggle()
}
}
}
}
}

import SwiftUI
struct ContentView: View {
let item: Item

init(item: Item) {
self.item = item
}

var body: some View {
ForEach(item.children) { item in
if item.children.isEmpty {
Text("(item.title)")
} else {
DisclosureGroup(
isExpanded: item.$isExpanded,
content: {
ContentView(item: item)
},
label: { Text("(item.title)") }
)
}
}
}
}
struct ContentView_Previews: PreviewProvider {

static var previews: some View {
let item: Item = dummyItems
ContentView(item: item)
}
}
struct Item: Identifiable {
var id: UUID = UUID()

@Binding var isExpanded: Bool
var title: String = "title"
var children: [Item] = []

init(title: String,
children: [Item]) {
self.title = title
self.children = children
self._isExpanded = .constant(true)
}
}
let dummyItems2 = Item(title: "root",
children: [
Item(title: "1",
children: [
Item(title: "1-1",
children: [
Item(title: "1-1-1",
children: [])]
),
Item(title: "1-2",
children: [
Item(title: "1-2-1",
children: []),
Item(title: "1-2-2",
children: [])]
)
]),
Item(title: "2",
children: [
Item(title: "2-1",
children: [
Item(title: "2-1-1",
children: [])]
),
Item(title: "2-2",
children: [
Item(title: "2-2-1",
children: [])]
),
Item(title: "2-3",
children: [
Item(title: "2-3-1",
children: [])]
),
]),
Item(title: "3",
children: [
Item(title: "3-1",
children: [
Item(title: "3-1-1",
children: []),
Item(title: "3-1-2",
children: []),
Item(title: "3-1-3",
children: [])]
),
Item(title: "3-2",
children: [
Item(title: "3-1-1",
children: [])]
),
Item(title: "3-3",
children: [
Item(title: "3-1-1",
children: [])]
)
])

])

let dummyItems = Item(title: "root",
children: [
Item(title: "1",
children: [
Item(title: "1-1",
children: [
Item(title: "1-1-1",
children: [])]
),
Item(title: "1-2",
children: [
Item(title: "1-2-1",
children: []),
Item(title: "1-2-2",
children: [])]
)
]),
Item(title: "2",
children: [
Item(title: "2-1",
children: [
Item(title: "2-1-1",
children: [])]
),
]),
Item(title: "3",
children: [
Item(title: "3-1",
children: [
Item(title: "3-1-1",
children: []),
Item(title: "3-1-2",
children: []),
Item(title: "3-1-3",
children: [])]
),
Item(title: "3-2",
children: [
Item(title: "3-1-1",
children: [])]
),
Item(title: "3-3",
children: [
Item(title: "3-1-1",
children: [])]
)
])

])

试试下面的

List {
if isChange {
ContentView(item: item)
} else {
ContentView(item: item2)
}
}
.id(isChange)    // << here !!

相关内容

  • 没有找到相关文章