在SwiftUI中从闭包返回视图

4

我有一个通用的区块视图组件,应该初始化为返回编辑该区块的视图和添加元素到该区块的另一个视图。

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)
    }
}
1个回答

0
我已经通过设置解决了它:
struct ProfileSection<Content, T> : View where Content : View, T : View {

    var model:ProfileSectionModel? = nil
    var sectionType:ProfileSectionType = .editable
    var onClickAdd:(() -> T)? = nil
    var content: Content

我可以像这样使用它:
ProfileSection<ForEach, AddIdentificationView>(m.identifications(), sectionType: .addable, editDialog: {
    AddIdentificationView()
}){
    ForEach( 0 ..< m.identifiers().count ) {
        ProfileEditableItem(key: m.identifiers()[$0].title, value: m.identifiers()[$0].value)
    }
}

接下来,AddIdentificationView将以模态视图的形式呈现。如果我摆脱<ForEach会更好,但现在这样做也可以。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接