如何在SwiftUI中的Preview provider中初始化数据

时间:2019-11-30 06:46:12

标签: swift xcode swiftui

我正在尝试从本地主机获取数据,使用列表视图列出帖子,然后将数据传递给CustomDetailView。这是我的NetworkManager代码: enter image description here

我的ListView: enter image description here

和StoryDe​​tails视图: enter image description here

那我要传递给StoryDe​​atils_Preview什么?

这是StoryDe​​tails代码

import SwiftUI

struct StoryDetails: View {
    var story: Story
    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                Text("story #123456")
                    .font(.callout)
                    .foregroundColor(Color.gray)
                Spacer()
                Text("5 days ago")
                    .font(.callout)
                    .foregroundColor(Color.gray)
                Button(action:{
                    print("Hello there")
                }){
                    Image(systemName:"info.circle").resizable()
                        .frame(width:22.0, height:22.0)
                        .accentColor(Color.gray)
                }
            }
            Text(story.body)
                .foregroundColor(.black)
                .kerning(1)
                .lineLimit(nil)
            HStack {
                Button(action: {
                    print("Hello World")
                }){
                    HStack {
                        Image(systemName:"heart")
                            .accentColor(.black)
                        Text("233")
                            .foregroundColor(.black)
                    }
                    .padding(.trailing)
                    HStack {
                        Image(systemName:"bubble.left")
                            .accentColor(.black)
                        Text("45")
                            .foregroundColor(.black)
                    }
                }
            }
        }
    }   
}

struct StoryDetails_Previews: PreviewProvider {
    static var previews: some View {
        StoryDetails(
            story: Story(
                id: 1,
                author: 1,
                body: "Testing",
                edited_time: "September 2019",
                pub_date: "October 2018",
                comments: [Comment](),
                story_likes: [StoryLike]()
             )
        )
    }
}

错误: enter image description here

1 个答案:

答案 0 :(得分:0)

您好,首先我需要看StoryDetails(),但是如果StoryDe​​tails一个故事,则应该在内部将其声明为var story: Story,让我在示例代码中进行更多说明: 在这里,您可以看到我的网络管理员课程:

class NetworkManager: ObservableObject {
    let url: String = "https://jsonplaceholder.typicode.com/todos/1"
    var objectWillChange = PassthroughSubject<NetworkManager, Never>()

    init() {
        fetchData()
    }

    @Published var user: User? {
        didSet {
            objectWillChange.send(self)
            print("set user")
        }
    }
    func fetchData() {
        guard let url = URL(string: url) else {return}
        print("fetch data")
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard error == nil else {return}
            print("no error")
            guard let data = data else {return}
            print("data is valid")
            let user = try! JSONDecoder().decode(User.self, from: data)
            DispatchQueue.main.async {
                self.user = user
            }
        }.resume()
    }
}

这是我的内容视图,其中在其中初始化了网络管理器:

struct ContentView: View {

    @ObservedObject var networkManager = NetworkManager()
    var body: some View {
        VStack {
            DetailsView(user: networkManager.user)
        }
    }
}

Details视图结构包含用户变量:

struct DetailsView: View {
    var user: User?
    var body: some View {
        VStack {
            Text("id: \(user?.id ?? 0)")
            Text("UserID: \(user?.userId ?? 0 )")
            Text("title: \(user?.title ?? "Empty")")
        }
    }
}

这就是DetailsView,正如您在此结构内部看到的那样,我声明需要传递类型为User的用户对象,因此,如果要在PreviewProvider中显示它,就像下面的代码

struct DetailsView_Previews: PreviewProvider {
    static var previews: some View {
        DetailsView(user: User(id: 0, userId: 0, title: "hello", completed: false)
    }
}

型号:

struct User: Decodable {
    var userId: Int = 0
    var id: Int = 0
    var title: String = ""
    var completed: Bool = false
}
  

PS:可以肯定的是,您可以比这种方式提供更好的包装   任何零例外都只是POC