我在这里有一个自定义的Picker,如果我使用普通的Picker的话,我的图像会被渲染得很大。
问题是,我没有让它以编程方式工作。它一直有效,直到我插入
来自我的模型的数据。
我试过用拆封、标签和id,但都不管用。
我知道,图像目前不会改变,但如果我让Picker以某种方式改变值,我会努力弄清楚这一点。
代码如下,包含所属部分:
@Query private var bonsai: [BonsaiModel]
@State private var selectedBonsai: BonsaiModel?
Section("Select Bonsai:") {
LabeledContent("Bonsai") {
HStack {
Image("d2")
.renderingMode(Image.TemplateRenderingMode.original)
.resizable()
.scaledToFit()
.frame(maxWidth: 60, maxHeight: 35)
.clipShape(RoundedRectangle(cornerRadius: 3))
Menu {
// put the picker inside a menu, so users see the images in the menu
Picker(selection: $selectedBonsai) {
ForEach(bonsai) { item in
Label {
if let spec = item.species {
Text(spec.name)
.foregroundColor(Color("plainTextColor"))
.font(.footnote)
.fontWeight(.semibold)
} else {
Text("No species selected.")
.foregroundColor(Color("plainTextColor"))
.font(.footnote)
.fontWeight(.semibold)
}
} icon: {
if let imageData = item.bonsaiImageData, // unwrapp data from item.image and store in imageData
let uiImage = UIImage(data: imageData) { // Put imgageData in UIImage and store image in uiImage
Image(uiImage: uiImage)
} else {
Image(systemName: "tree")
}
}.id(item)
}
} label: { }
} label: {
HStack {
if let species = selectedBonsai {
Text(species.name)
.foregroundColor(Color("plainTextColor"))
.font(.footnote)
.fontWeight(.semibold)
} else {
Text("No species selected.")
.foregroundColor(Color("plainTextColor"))
.font(.footnote)
.fontWeight(.semibold)
}
Image(systemName: "chevron.up.chevron.down")
}
.tint(.secondary)
.imageScale(.small)
}
}
}
}
选取器如下所示:
谢谢:)