如何更新可观察的对象类,之后picker -swiftui更新了值

发布于 2025-02-06 19:37:46 字数 2680 浏览 2 评论 0原文

我有一个可观察到的类,该类根据月和年价值获取远程数据。最初,它可以正常工作,因为我使用当前的一个月和年值,但是我想更新并重新运行getAttEndanceRecord2当我从Picker中选择其他月时。实现这一目标的最佳实践是什么?

struct AttendanceRecord: View {
    
    @ObservedObject var item_data: getAttendanceRecord2
    
    let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November","December"]
    
    init(id: String) {
        self.item_data = getAttendanceRecord2(id: id,month: getMonth(), year: getYear())
    }
    
    var body: some View {
        
        VStack {
            
            Picker(selection: $selectedMonth, label: Text("Months"), content: {
                ForEach(months, id: \.self) {
                    Text($0)
                }
            }).pickerStyle(MenuPickerStyle())
            
            Text("You selected: \(selectedMonth)")
        }
    }
}

这是我的功能:

class getAttendanceRecord2: ObservableObject {
    
    @Published var attlist = [EAttendance]()
        
    init(id: String, month: String, year: String) {
        
        let url = URL(string: "http://superteclabs.com/apis2/AttendanceRecord2.php")
        var request = URLRequest(url: url!)
        request.httpMethod = "POST"
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Accept")
        let formdata: Data = "id=\(id)&month=\(month)&year=\(year)".data(using: .utf8)!
        request.httpBody = formdata
        
        URLSession.shared.dataTask(with: request) { (response_data, response, error) in
            guard error == nil else {
                print("Error: error calling POST")
                print(error!)
                return
            }
            guard let data = response_data else {
                print("Error: Did not receive data")
                return
            }
            guard let response = response as? HTTPURLResponse, (200 ..< 299) ~= response.statusCode else {
                print("Error: HTTP request failed")
                return
            }
            
            do {
                
                let decodedData = try JSONDecoder().decode([EAttendance].self, from:data)
                DispatchQueue.main.async {
                    self.attlist = decodedData
                }    
            } catch {
                print("Error: Trying to convert JSON data to string")
                return
            }
        }.resume()
    }  
}

I have an ObservableObject class that fetches the remote data based on month and year value. Initially it works fine because I use current month and year values however I want to update and re run the getAttendanceRecord2 when I select some other month from picker. What is the best practice for achieving this?

struct AttendanceRecord: View {
    
    @ObservedObject var item_data: getAttendanceRecord2
    
    let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November","December"]
    
    init(id: String) {
        self.item_data = getAttendanceRecord2(id: id,month: getMonth(), year: getYear())
    }
    
    var body: some View {
        
        VStack {
            
            Picker(selection: $selectedMonth, label: Text("Months"), content: {
                ForEach(months, id: \.self) {
                    Text($0)
                }
            }).pickerStyle(MenuPickerStyle())
            
            Text("You selected: \(selectedMonth)")
        }
    }
}

Here is my function:

class getAttendanceRecord2: ObservableObject {
    
    @Published var attlist = [EAttendance]()
        
    init(id: String, month: String, year: String) {
        
        let url = URL(string: "http://superteclabs.com/apis2/AttendanceRecord2.php")
        var request = URLRequest(url: url!)
        request.httpMethod = "POST"
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Accept")
        let formdata: Data = "id=\(id)&month=\(month)&year=\(year)".data(using: .utf8)!
        request.httpBody = formdata
        
        URLSession.shared.dataTask(with: request) { (response_data, response, error) in
            guard error == nil else {
                print("Error: error calling POST")
                print(error!)
                return
            }
            guard let data = response_data else {
                print("Error: Did not receive data")
                return
            }
            guard let response = response as? HTTPURLResponse, (200 ..< 299) ~= response.statusCode else {
                print("Error: HTTP request failed")
                return
            }
            
            do {
                
                let decodedData = try JSONDecoder().decode([EAttendance].self, from:data)
                DispatchQueue.main.async {
                    self.attlist = decodedData
                }    
            } catch {
                print("Error: Trying to convert JSON data to string")
                return
            }
        }.resume()
    }  
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只怪假的太真实 2025-02-13 19:37:46

可以在onchange中完成(of:,喜欢

Picker(selection: $selectedMonth, label: Text("Months"), content: {
    ForEach(months, id: \.self) {
        Text($0)
 }
}).pickerStyle(MenuPickerStyle())
.onChange(of: selectedMonth) { newMonth in           // << here !!
   // process here new selected month as needed
}

It can be done in onChange(of:, like

Picker(selection: $selectedMonth, label: Text("Months"), content: {
    ForEach(months, id: \.self) {
        Text($0)
 }
}).pickerStyle(MenuPickerStyle())
.onChange(of: selectedMonth) { newMonth in           // << here !!
   // process here new selected month as needed
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文