【发布时间】:2021-08-27 14:52:11
【问题描述】:
我有几个不同的选择器用于选择与输入交易相关的选项。我为用户提供了一种预设模板的方法,他们可以按这些模板自动填充选择器。
这是我遇到问题的选择器之一的一些代码。此选择器在手动选择类别时工作正常。
Picker("Category", selection: $category, content: {
ForEach(user.categories, id: \.self) { category in
Text(category.name)
.tag(category as Category?)
}
})
有一个用于模板本身的选择器。当用户选择一个模板时,它使用onChange 来填充其他选择器。 savedTransaction 是模板。我之前使用了不同的名称,并且没有更新它。
.onChange(of: savedTransaction, perform: { value in
if savedTransaction != nil {
//set fields
type = savedTransaction!.transaction.type
if type == .expense {
category = savedTransaction!.transaction.category
if savedTransaction!.transaction.subcategory != nil {
subcategory = savedTransaction!.transaction.subcategory
}
}
amount = savedTransaction!.transaction.amount
if savedTransaction!.transaction.note != nil {
note = savedTransaction!.transaction.note!
}
}
})
一旦用户选择了模板,他们就可以添加交易。运行一些东西来添加事务,然后使用此代码清除字段。
//Clear fields
savedTransaction = nil
date = Date()
type = .income
category = nil
subcategory = nil
amount = 0.0
note = ""
当用户第一次这样做时,这项工作很好。之后,当他们选择相同的模板时,“类别”选择器将不再填充。
category = savedTransaction!.transaction.category
我在上面看到的行之后运行了print(category),类别将被正确设置,但是选择器本身不会显示。您必须手动选择类别才能显示。即使category 不是零,什么会导致选择器不显示选择的内容?如果您需要更多信息,请告诉我。
编辑:添加了此代码,但发现它按预期工作。它应该类似于我在我的应用程序中所做的。我现在正试图找出不同之处。模板与 SavedTransaction 相同。
内容视图
import SwiftUI
struct ContentView: View {
var user = User()
@State var template: Template?
@State var category: Category?
var body: some View {
NavigationView {
List {
Picker("Template", selection: $template, content: {
ForEach(user.templates, id: \.self) { template in
Text(template.name)
.tag(template as Template?)
}
})
.onChange(of: template, perform: { value in
if template != nil {
category = template!.category
print(category)
}
})
Picker("Category", selection: $category, content: {
ForEach(user.categories, id: \.self) { category in
Text(category.name)
.tag(category as Category?)
}
})
Button("Add") {
template = nil
category = nil
}
}
.listStyle(InsetGroupedListStyle())
}
}
}
用户结构
struct User: Codable, Hashable {
var templates = [Template()]
var categories = [Category()]
}
模板结构
struct Template: Codable, Hashable {
var name = "Test Template"
var category = Category()
}
分类结构
struct Category: Codable, Hashable {
var name = "Test Category"
}
【问题讨论】:
-
你能想出一个minimal reproducible example吗?现在,我会担心
category as Category?,因为这意味着您的selection类型与您的tag类型不同,这会导致问题。 -
@jnpdx 所以唯一的原因是
category是这样初始化的@State var category: Category?。如果我不使用category as Category,选择器不会选择任何东西。 -
好的。就像我说的,minimal reproducible example 会有所帮助。
-
@jnpdx 我添加了一些代码,应该会重现该问题。如果这不起作用,请告诉我。
-
听起来是个不错的调试项目。一种方法是用您的工作示例替换您拥有的内容,然后重新添加差异,直到找到罪魁祸首。