在我的SwiftUI
项目中,我有一个按钮class
模型:
import SwiftUI
import Combine
class Button: Identifiable, ObservableObject {
var id = UUID()
@Published var title = String()
init(title: String) {
self.title = title
}
func changeTitle(title: String) {
self.title = title
}
}
然后我有另一个class
名称ControlPanel
,它有一个 Button 数组作为参数。
class ControlPanel: Identifiable, ObservableObject {
var id = UUID()
@Published var name = String()
@Published var buttons:[Button] = []
init(name: String) {
self.name = name
}
}
UIViewControllerRepresentable
我必须在我用一个类构建的自定义集合视图中收听这个数组:
struct ButtonCollectionView: UIViewControllerRepresentable {
@Binding var buttons: [Button]
func makeUIViewController(context: Context) -> UICollectionViewController {
let vc = CollectionViewController(collectionViewLayout: .init())
vc.buttonArray = buttons
return vc
}
func updateUIViewController(_ uiViewController: UICollectionViewController, context: Context) {
if let vc = uiViewController as? CollectionViewController {
vc.buttonArray = buttons
vc.collectionView.reloadData()
}
}
}
最后,我在内容视图中调用此集合视图,方法如下:
@ObservedObject var controlPanel: ControlPanel = ControlPanel(name: "test")
var body: some View {
ButtonCollectionView(button: $controlPanel.buttons)
}
当我加载我的内容视图时,我确实得到了所有单元格,但是一旦我更改它们,视图就不会更新。我该如何解决这个问题?