2

我在视图中使用 ObservableObject 的数组存在问题。我有一个空数组。我在 onAppear 页面调用了一个函数。当数据返回时,视图不会使用数组中的新数据更新:

class NewsState: ObservableObject {

    private let base: String = "api"
    let objectWillChange = ObservableObjectPublisher()

    @Published var wagsList: Array<UserSlider> = [] {
        willSet {
            objectWillChange.send()
        }
    }

    func getList() {
        let url = NSURL(string: "\(base)/UserApi/getList")
        var mutableURLRequest = URLRequest(url: url! as URL)
        mutableURLRequest.httpMethod = "GET"
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        AF.request(mutableURLRequest).responseData { response in
            guard let data = response.data else { return }
            let resp = try! JSONDecoder().decode(Array<UserSlider>.self, from: data)
            for i in resp {
                let userSlider = UserSlider(id: i.id, uid: i.uid, image: i.image)
                self.wagsList.append(userSlider)
            }
        }
    }
}

在我看来,我有这个:

HStack {
                                ScrollView(.horizontal, showsIndicators: false) {
                                    HStack(spacing: 20) {
                                        if(self.newsState.wagsList.count != 0) {
                                            ForEach(self.newsState.wagsList, id: \.self) { wags in
                                                VStack {
                                                    HStack {
                                                        URLImage(URL(string: "\(wags.image)")!, expireAfter: Date(timeIntervalSinceNow: 10)) { proxy in
                                                            proxy.image
                                                                .renderingMode(.original)
                                                                .resizable()
                                                                .aspectRatio(contentMode: .fill)
                                                                .frame(width: 60, height: 60)
                                                                .clipShape(Circle())
                                                                .overlay(
                                                                    RoundedRectangle(cornerRadius: 30)
                                                                        .stroke(Color.white, lineWidth: 2)
                                                                )
                                                                .contentShape(Circle())
                                                        }.frame(width: 62, height: 62)
                                                    }
                                                    HStack {
                                                        Text("10K")
                                                            .foregroundColor(Color.white)
                                                            .font(Font.custom("Metropolis-Bold", size: 15))
                                                    }
                                                    HStack {
                                                        Text("followers")
                                                            .foregroundColor(Color.white)
                                                            .font(Font.custom("Metropolis-Normal", size: 15))
                                                    }
                                                }
                                            }
                                        } else {
                                            //loader
                                        }
                                    }.onAppear(perform: initPage)
                               }
                            }

我哪里错了?我已经看到问题是由 ScrollView 引起的

4

2 回答 2

0

试试这个

class NewsState: ObservableObject {

    private let base: String = "api"

    @Published var wagsList: Array<UserSlider> = []

    func getList() {
        let url = NSURL(string: "\(base)/UserApi/getList")
        var mutableURLRequest = URLRequest(url: url! as URL)
        mutableURLRequest.httpMethod = "GET"
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        AF.request(mutableURLRequest).responseData { response in
            guard let data = response.data else { return }
            let resp = try! JSONDecoder().decode(Array<UserSlider>.self, from: data)

            let results = resp.map { UserSlider(id: $0.id, uid: $0.uid, image: $0.image) }
            DispatchQueue.main.async {
                self.wagsList = results
            }
        }
    }
}
于 2020-05-26T09:36:27.383 回答
0

因为我不清楚错误可能在哪里。它可能getList在您的视图中或视图中。

这是一个简单的示例,说明它如何与 aPublished和一起工作ObserverdObject: 注意:您的 getList 函数不在此解决方案中,因为错误可能与您的 API、JSON 等有关。

import SwiftUI

struct ContentView: View {

    @ObservedObject var state = NewsState()

    var body: some View {
        Group { //needed for the IF Statement below
            if state.stringList.count > 0 {
                ForEach(self.state.stringList, id: \.self){ s in
                    Text(String(s))
                }
            }
        }.onTapGesture {
            self.state.getNewList()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


class NewsState: ObservableObject {

    @Published var stringList: Array<String> = []

    init() {
        self.getList()
    }

    func getList() {
        self.stringList.append("New")
    }

    func getNewList() {
        self.stringList = []
        self.stringList.append("New new")
    }
}

于 2020-05-26T10:14:35.880 回答