我有一个通用的区块视图组件,应该初始化为返回编辑该区块的视图和添加元素到该区块的另一个视图。
import SwiftUI
enum ProfileSectionType {
case editable
case addable
}
struct ProfileSection<Content> : View where Content : View {
var model:ProfileSectionModel? = nil
var sectionType:ProfileSectionType = .editable
var onClick:(() -> View)? = nil
var content: Content
@inlinable public init(_ model:ProfileSectionModel? = nil, sectionType:ProfileSectionType = .editable, @ViewBuilder content: () -> Content) {
self.model = model
self.content = content()
self.sectionType = sectionType
}
var body : some View {
switch sectionType {
case .editable:
return AnyView(editable())
case .addable:
return AnyView(addable())
}
}
}
但不可能像这样使用闭包 (() -> View)
。我可以将其作为参数传递给init,但是那样我就无法获得视图的懒加载。
我还尝试过在枚举中使用泛型。我的第一次尝试类似于:
enum ProfileSectionType<T : View> {
case editable
case addable(viewForAdding:T)
}
但是这似乎使得问题更加复杂了。如何让这个部分创建两个不同的视图,一个用于编辑,另一个用于添加?
我希望能像这样使用它:
ProfileSection(m.identifications(), sectionType: .addable, onClick: ^{
AddIdentificationView()
}){
ForEach( 0 ..< m.identifiers().count ) {
ProfileEditableItem(key: m.identifiers()[$0].title, value: m.identifiers()[$0].value)
}
}