gpt4 book ai didi

SwiftUI Picker 不与 ObservedObject 绑定(bind)

转载 作者:行者123 更新时间:2023-12-05 05:04:02 24 4
gpt4 key购买 nike

我正在尝试使用从外部 API 异步获取的数据填充选择器。

这是我的模型:

struct AppModel: Identifiable {
var id = UUID()
var appId: String
var appBundleId : String
var appName: String
var appSKU: String
}

获取数据并发布的类是:

class AppViewModel: ObservableObject {
private var appStoreProvider: AppProvider? = AppProvider()
@Published private(set) var listOfApps: [AppModel] = []
@Published private(set) var loading = false

fileprivate func fetchAppList() {
self.loading = true
appStoreProvider?.dataProviderAppList { [weak self] (appList: [AppModel]) in
guard let self = self else {return}
DispatchQueue.main.async() {
self.listOfApps = appList
self.loading = false
}
}
}
init() {
fetchAppList()
}
}

View 是:

struct AppView: View {
@ObservedObject var appViewModel: AppViewModel = AppViewModel()
@State private var selectedApp = 0

var body: some View {
ActivityIndicatorView(isShowing: self.appViewModel.loading) {
VStack{
// The Picker doesn't bind with appViewModel
Picker(selection: self.$selectedApp, label: Text("")) {
ForEach(self.appViewModel.listOfApps){ app in
Text(app.appName).tag(app.appName)
}
}
// The List correctly binds with appViewModel
List {
ForEach(self.appViewModel.listOfApps){ app in
Text(app.appName.capitalized)
}
}
}
}
}
}

虽然 List View 与观察对象 appViewModel 绑定(bind),但 Picker 的行为方式不同。我不明白为什么。有什么帮助吗?

最佳答案

我提交了错误报告,FB7670992。 Apple 昨天回应,建议我在 iOS 14 beta 1 中确认此行为。现在看来已经解决。

struct ContentView: View {
@ObservedObject var viewModel = ViewModel()

var body: some View {
Picker("", selection: $viewModel.wheelPickerValue) {
ForEach(viewModel.objects) { object in
Text(object.string)
}
}
.pickerStyle(WheelPickerStyle())
.labelsHidden()
}
}

在哪里

struct Object: Identifiable {
let id = UUID().uuidString
let string: String
}

class ViewModel: ObservableObject {
private var counter = 0

@Published private(set) var objects: [Object] = []
@Published var segmentedPickerValue: String = ""
@Published var wheelPickerValue: String = ""

fileprivate func nextSetOfValues() {
let newCounter = counter + 3
objects = (counter..<newCounter).map { value in Object(string: "\(value)") }
let id = objects.first?.id ?? ""
segmentedPickerValue = id
wheelPickerValue = id
counter = newCounter
}

init() {
let timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] timer in
guard let self = self else { timer.invalidate(); return }
self.nextSetOfValues()
}
timer.fire()
}
}

结果:

enter image description here

关于SwiftUI Picker 不与 ObservedObject 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61290708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com