gpt4 book ai didi

swiftui - 如何在 SwiftUI 中更新单个 subview ?

转载 作者:行者123 更新时间:2023-12-01 18:43:03 24 4
gpt4 key购买 nike

我正在尝试在 subview 和父 View 之间建立 SwiftUI 连接。通过单击任何 subview ,我只想重绘已点击的 View ,而不是整个父 View 。

下面的当前实现不允许您在单击 View 时重绘 View ,因为它具有派生值。

我通过将 BindableObject 协议(protocol)添加到 CustomColor 尝试了不同的场景,但没有成功。

class CustomColor: Identifiable {

let id = UUID()
var color: Color

init(color: Color) {
self.color = color
}

func change(to color: Color) {
self.color = color
}

}

class ColorStore: BindableObject {

var colors: [CustomColor] = [] {
didSet {
didChange.send(self)
}
}

var didChange = PassthroughSubject<ColorStore, Never>()

init() {
self.colors = Array.init(repeating: CustomColor(color: .red), count: 10)
}

}


struct ContentView: View {

@EnvironmentObject var colorStore: ColorStore

var body: some View {
NavigationView {
List {
ForEach(colorStore.colors) { color in
ColorShape(color: color)
}
}.navigationBarTitle(Text("Colors"))
}
}

}

struct ColorShape: View {

var color: CustomColor

var body: some View {
Button(action:
{ self.color.change(to: .blue) }
, label: {
ShapeView(shape: Circle(), style: color.color)
})
}

}

Here is the UI I have

最佳答案

我想我已经找到解决方案了。第一个问题是我通过重复相同的元素而不是添加独立的元素来初始化颜色数组。

更重要的是,CustomColor 本身应该具有 BindableObject 一致性,而不是模型(我们不更改颜色数组,我们更改每种颜色)。最后,我们不需要将对象包装在 ForEach 元素中(这样就失去了可重用性),而是将它们放在 List 元素中。

通过此实现,只有已更改的 View 才会重绘,而不是整个集合。

这是代码:

class CustomColor: BindableObject, Identifiable {

var didChange = PassthroughSubject<CustomColor, Never>()

let id = UUID()
var color: Color {
didSet {
self.didChange.send(self)
}
}

init(color: Color) {
self.color = color
}

func change(toColor color: Color) {
self.color = color
}

}

class ColorStore {

var colors: [CustomColor] = []

init() {
(0...10).forEach { _ in colors.append(CustomColor(color: .red)) }
}

}


struct ContentView: View {

let colorStore: ColorStore

var body: some View {
NavigationView {
List(colorStore.colors) { color in
ColorShape(color: color)
}.navigationBarTitle(Text("Colors"))
}
}

}

struct ColorShape: View {

@ObjectBinding var color: CustomColor

var body: some View {
Button(action: { self.color.change(toColor: .blue) }, label: {
ShapeView(shape: Circle(), style: color.color)
})
}

}

关于swiftui - 如何在 SwiftUI 中更新单个 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56506591/

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