使结构列表符合 SwiftUI 协议

问题描述 投票:0回答:1

我有一个自定义协议

protocol CustomProtocol {}

我有一个自定义结构说

struct CustomStruct: View, CustomProtocol

如何使(CustomStruct,CustomStruct)符合CustomProtocol

我有一个自定义 ViewBuilder,它有一个 init 函数,

init<views>(@ViewBuilder content: @escaping () -> TupleView<Views>)

现在我只想接受符合

CustomProtocol
的视图

示例:

struct CustomStruct: View {
var views: [AnyView]

init<Views: CustomProtocol>(@ViewBuilder content: @escaping () -> TupleView<Views>) {
    self.views = content().getViews
}

我为 getViews 变量添加了元组视图的扩展:

extension TupleView {
var getViews: [AnyView] {
    makeArray(from: value)
}

private struct GenericView {
    let body: Any
    
    var anyView: AnyView? {
        AnyView(_fromValue: body)
    }
}

private func makeArray<Tuple>(from tuple: Tuple) -> [AnyView] {
    func convert(child: Mirror.Child) -> AnyView? {
        withUnsafeBytes(of: child.value) { ptr -> AnyView? in
            let binded = ptr.bindMemory(to: GenericView.self)
            return binded.first?.anyView
        }
    }
    
    let tupleMirror = Mirror(reflecting: tuple)
    return tupleMirror.children.compactMap(convert)
}

}

swift swiftui swift-protocols
1个回答
1
投票

我能想到的唯一方法就是重新发明你自己的

ViewBuilder
:

@resultBuilder
struct MyCustomViewBuilder {
    static func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> TupleView<(C0, C1)> where C0 : View & CustomProtocol, C1 : View & CustomProtocol {
        ViewBuilder.buildBlock(c0, c1)
    }
    static func buildBlock<C0, C1, C2>(_ c0: C0, _ c1: C1, _ c2: C2) -> TupleView<(C0, C1, C2)> where C0 : View & CustomProtocol, C1 : View & CustomProtocol, C2: View & CustomProtocol {
        ViewBuilder.buildBlock(c0, c1, c2)
    }

    // and so on... add every method in ViewBuilder here
}

在 Swift 5.9+ 中,您可以使用参数包编写

buildBlock

static func buildBlock<each Content>(_ content: repeat each Content) -> TupleView<(repeat each Content)> where repeat each Content : View & CustomProtocol {
    ViewBuilder.buildBlock(repeat each content)
}

在 Swift 5.9 之前,

ViewBuilder
具有最多 10 个视图的
buildBlock
重载(这就是为什么你不能在
ViewBuilder
中放置超过 10 个视图),因此你需要编写 10 个
buildBlock
重载如果您想要与
ViewBuilder
相同的功能。

那么你可以这样做:

struct CustomStack<Views>: View {
    var body: some View {
        content
    }
    
    let views: [AnyView]
    let content: TupleView<Views>

    // note the change from @ViewBuilder to @CustomViewBuilder
    init(@MyCustomViewBuilder content: @escaping () -> TupleView<Views>) {
        let view = content()
        self.views = view.getViews
        self.content = view
    }
}

现在如果你这样做:

CustomStack {
    Text("Hello")
    Text("World")
}

编译器会抱怨

Text
不符合
CustomProtocol

© www.soinside.com 2019 - 2024. All rights reserved.