我從 Model() 中獲取圖片的框架顏色名稱,我從 colorSet 中獲取顏色
struct Model: Identifiable {
let id = UUID()
let image: String
let colorSet: String
}
extension Model {
static func AllModel() -> [Model] {
return [
//1
Model(image: "folder", colorSet: "YELLOW"),
//2
Model(image: "folder.fill", colorSet: "")
]
}
}
但是,如果 colorSet 因為不需要而沒有顏色名稱,則會出現錯誤

如果顏色名稱不在 colorSet 中,如何做到這一點,則不顯示任何內容
完整代碼
struct Model: Identifiable {
let id = UUID()
let image: String
let colorSet: String
}
extension Model {
static func AllModel() -> [Model] {
return [
//1
Model(image: "folder", colorSet: "YELLOW"),
//2
Model(image: "folder.fill", colorSet: "")
]
}
}
struct Im: View {
let model = Model.AllModel()
var body: some View {
HStack {
ForEach(model) { model in
CellView(model: model)
}
}
}
}
struct CellView: View {
let model: Model
var body: some View {
Image(systemName: model.image)
.resizable()
.scaledToFit()
.frame(width: 40, height: 40)
.padding()
.overlay(RoundedRectangle(cornerRadius: 9)
.stroke(Color(model.colorSet), lineWidth: 5))
}
}

uj5u.com熱心網友回復:
只是要清楚:
extension Model {
static func AllModel() -> [Model] {
return [
//1
Model(image: "folder", colorSet: "YELLOW"),
//2
Model(image: "folder.fill", colorSet: "CLEAR")
]
}
}
像這樣設定“CLEAR”顏色集:

結果,你會得到這個:

編輯:
由于您還在圖示下方顯示顏色的名稱,因此您需要做的就是使用三元組來查看是否colorSet == "CLEAR"然后用空字串替換它,如下所示:
struct CellView: View {
let model: Model
var body: some View {
VStack {
Image(systemName: model.image)
.resizable()
.scaledToFit()
.frame(width: 40, height: 40)
.padding()
.overlay(RoundedRectangle(cornerRadius: 9)
.stroke(Color(model.colorSet), lineWidth: 5))
// Put a ternary in the Text() to test whether you have "CLEAR"
Text(model.colorSet == "CLEAR" ? "" : model.colorSet)
}
}
}
uj5u.com熱心網友回復:
我會讓你的模型更豐富,所以你的視圖更簡單
struct Model: Identifiable {
let id = UUID()
let image: String
let colorSet: String? // optional named color
}
extension Model {
static func AllModel() -> [Model] {
return [
//1
Model(image: "folder", colorSet: "YELLOW"),
//2
Model(image: "folder.fill", colorSet: nil)
]
}
// Computed property for the color
var borderColor: Color {
guard let colorSet = colorSet else {
return .clear
}
return Color(colorSet)
}
// and e.g. for a name for showing in the UI
var uiName: String {
guard let colorSet = colorSet else {
return "None"
}
return colorSet
}
}
然后你的觀點變成
struct CellView: View {
let model: Model
var body: some View {
Image(systemName: model.image)
.resizable()
.scaledToFit()
.frame(width: 40, height: 40)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 9)
.stroke(model.borderColor, lineWidth: 5)
)
}
}
對文本類似,其名稱已格式化為在模型中顯示,而不是在視圖中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/446758.html
