SwiftUI不能绑定类数组参数

问题描述

在我的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的{​​{1}},它具有一个Button数组作为参数。

ControlPanel

我必须在用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()
        }
    }
}

当我加载内容视图时,我确实会获得所有单元格,但是一旦更改它们,视图将不会更新。我该如何解决这个问题?

解决方法

您的Button已经在另一个@Published属性中,因此@Published var title无法正常工作。

最简单的解决方案是使您的Button成为 struct (并将其重命名为SwiftUI尚未使用的名称,例如CustomButton):

struct CustomButton: Identifiable {
    var id = UUID()
    var title = ""
    
    mutating func changeTitle(title: String) {
        self.title = title
    }
}

有关更多高级解决方案,请参见:How to tell SwiftUI views to bind to nested ObservableObjects