【问题标题】:SwiftUI can't bind class array parameterSwiftUI 无法绑定类数组参数
【发布时间】:2020-09-02 15:33:52
【问题描述】:

在我的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
    }
}

然后我有另一个名为ControlPanelclass,它有一个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)
}

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

【问题讨论】:

    标签: swift swiftui observableobject uiviewrepresentable


    【解决方案1】:

    您的Button 已经在另一个@Published 属性中,因此@Published var title 将不起作用。

    最简单的解决方案是将Button 设为结构(并将其重命名为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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      • 2021-12-30
      相关资源
      最近更新 更多