如何将ObservableObject viewModel中的GENERIC @Published属性传递给视图?

时间:2020-05-28 18:14:23

标签: generics swiftui swift-protocols swiftui-list

如何将ObservableObject viewModel中的通用@Published属性传递给视图? @Published是否可以观察到泛型变量?

协议声明:

protocol SectionHeaderViewObject {
         var name: String
         var iconName: String
         ...
    }

我省略了customObject1和customObject2对SectionHeaderViewGenerator的实现。 这是viewModel和headerView。

struct ListViewModel: ObservableObject {
   @Published var sections: [customObject1 : [Int]] = [:]

   enum Sort {
      case customObject1, customObject2
   }

   var sort: Sort {
      didSet {
          switch self {
              case .customObject1:
                        sections = [CustomObject1():[1]]
              case .customObject2:
                        sections = [CustomObject2():[1]]
          }
       }
   }
}

struct SectionHeaderView<T: SectionHeaderViewGenerator> {
    var customObject: T
    var body: some View {
         HStack {
            Text(customObject.name)
            Image(customObject.iconName)
    }
}

通过视图调用:

struct ListView: View {
    @ObservedObject var viewModel: ListViewModel
    var body: some View {
        List {
           Section(header: SectionHeaderView(customObject: viewModel.customObject) {
                  aRowView()
             }
        }

}

我想做这样的事情。但是我很难对sections字典的键实现泛型。

@Published var sections: [SectionHeaderViewObject : Int] = [:]

实际上是通过组合:

@Published var sections: [customObject1 : Int] = [:]
@Published var sections: [customObject2 : Int] = [:]

0 个答案:

没有答案