在SwiftUI中将数据传递到ViewBuilder闭包中的正确方法是什么?

时间:2020-06-20 16:27:50

标签: swift list generics swiftui viewbuilder

我在SwiftUI中使用泛型,在尝试利用ViewBuilder闭包将数据传递到泛型View时遇到了数据持久性问题。我的目标是拥有一个shell视图,该视图管理从API接收数据并将其传递给在ViewBuilder块中定义的通用视图。所有数据似乎都已成功传递到init,包括传递给我的通用BasicListView,但是当body被调用时,列表数据都不会持久保存。

我认为通过代码解释问题会更容易。很抱歉在这里长代码转储:

import SwiftUI
import Combine

// This is the blank "shell" View that manages passing the data into the viewBuilder through the @ViewBuilder block

struct BlankView<ListItem, Content:View>: View where ListItem: Listable {
    
    let api = GlobalAPI.shared
    
    @State var list: [ListItem] = []
    
    @State var viewBuilder: ([ListItem]) -> Content // Passing in generic [ListItem] here
    
    init(@ViewBuilder builder: @escaping ([ListItem]) -> Content) {
        self._viewBuilder = State<([ListItem]) -> Content>(initialValue: builder)
    }
    
    var body: some View {
        
        viewBuilder(list) // List contained in Blank View passed into viewBuilder Block here
            .multilineTextAlignment(.center)
            .onReceive(GlobalAPI.shared.listDidChange) { item in
                if let newItem = item as? ListItem {
                    self.list.append(newItem) // Handle API updates here
                }
            }
    }
}

// And Here is the implementation of the Blank View
struct TestView: View {

    public var body: some View {
        BlankView<MockListItem, VStack>() { items in // A list of items will get passed into the block
            VStack {
                Text("Add a row") // Button to add row via API singleton
                    .onTapGesture {
                        GlobalAPI.shared.addListItem()
                    }
                
                BasicListView(items: items) { // List view init'd with items
                    Text("Hold on to your butts") // Destination
                }
            }
        }
    }
}


// Supporting code

// The generic list view/cell

struct BasicListView<Content: View, ListItem:Listable>: View {
    
    @State var items: [ListItem]
    
    var destination: () -> Content
    
    init(items: [ListItem], @ViewBuilder builder: @escaping () -> Content) {
        self._items = State<[ListItem]>(initialValue: items) // Items successfully init'd here
        self.destination = builder
    }
    
    var body: some View {
        List(items) { item in // Items that were passed into init no longer present here, this runs on a blank [ListItem] array
            BasicListCell(item: item, destination: self.destination)
        }
    }
}

struct BasicListCell<Content: View, ListItem:Listable>: View {
    
    @State var item: ListItem
    
    var destination: () -> Content
    
    var body: some View {
        
        NavigationLink(destination: destination()) {
            HStack {
                item.photo
                    .resizable()
                    .frame(width: 50.0, height: 50.0)
                    .font(.largeTitle)
                    .cornerRadius(25.0)
                VStack (alignment: .leading) {
                    Text(item.title)
                        .font(.headline)
                    Text(item.description)
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
            }
        }
    }
}

// The protocol and mock data struct
protocol Listable: Identifiable {
        
    var id: UUID { get set }
    var title: String { get set }
    var description: String { get set }
    var photo: Image { get set }
}

public struct MockListItem: Listable {
    
    public var photo: Image = Image(systemName:"photo")
    public var id = UUID()
    public var title: String = "Title"
    public var description: String = "This is the description"

    static let all = [MockListItem(), MockListItem(), MockListItem(), MockListItem()]
}

// A global API singleton for testing data updates
class GlobalAPI {
    
    static let shared = GlobalAPI()
    
    var listDidChange = PassthroughSubject<MockListItem, Never>()
    
    var newListItem:MockListItem? = nil {
        didSet {
            if let item = newListItem {
                listDidChange.send(item)
            }
        }
    }
    
    func addListItem() {
        newListItem = MockListItem()
    }
}

这是否是ViewBuilder块的正确实现,还是不鼓励尝试通过View builder块传递数据?

注意:什么起作用

如果我直接传递静态Mock数据,则视图将正确绘制自身,如下所示:

struct TestView: View {

    public var body: some View {
        BlankView<MockListItem, VStack>() { items in // A list of items will get passed into the block
            VStack {
                Text("Add a row") // Button to add row via API singleton
                    .onTapGesture {
                        GlobalAPI.shared.addListItem()
                    }
                
                BasicListView(items: MockListItem.all) { // List view init'd with items
                    Text("Hold on to your butts") // Destination
                }
            }
        }
    }
}

有什么想法吗?感谢您的帮助并反馈大家。

2 个答案:

答案 0 :(得分:1)

这是固定的视图。您可以在外部提供模型,但是状态是用于内部更改的,一旦创建,状态就会在同一视图中保持不变。因此,在这种情况下,状态是错误的-视图重建由外部注入的数据管理。

通过Xcode 11.4 / iOS 13.4测试

demo

struct BasicListView<Content: View, ListItem:Listable>: View {

    var items: [ListItem]
    var destination: () -> Content

    init(items: [ListItem], @ViewBuilder builder: @escaping () -> Content) {
        self.items = items // Items successfully init'd here
        self.destination = builder
    }

    var body: some View {
        List(items) { item in // Items that were passed into init no longer present here, this runs on a blank [ListItem] array
            BasicListCell(item: item, destination: self.destination)
        }
    }
}

答案 1 :(得分:0)

欢迎,我想我想出了一个解决方法。

问题似乎出在BasicListView中的项目用@State而不是@Binding包裹,并且ViewBuilder块的类型为([ListItem]) -> Content而不是{ {1}}。最初的设置适用于从从块外部拉出的静态数据((Binding<[ListItem]>) -> Content)进行初始化,但是当使用传递到块中的数据时,在init与被调用主体之间的某个位置将被丢弃/重置。相反,我将MockListItem.all中的items更改为@Binding,现在通过传入BasicListView中的@State var list的绑定来进行初始化。这是更新的代码:

BlankView

希望这可以帮助某个人。干杯!