在 Swift 中根据 API 调用设置前景色
Posted
技术标签:
【中文标题】在 Swift 中根据 API 调用设置前景色【英文标题】:Set foreground colour based on API call in Swift 【发布时间】:2021-11-12 21:16:37 【问题描述】:我想呈现我构建的 API 的结果列表,并作为快速视觉参考供人们查看状态是红色、琥珀色还是绿色。
我可以将信息作为字符串或 int 发送回,我并不十分了解如何使用,但我无法在我使用的 sf 符号上更改前景色,即 circle.fill
我不确定将数据输入 SwiftUI 的最佳方式是什么,因为我不能只为我的颜色名称声明一个字符串。
目前它来自一个变量名,它是我的结构的一部分,但我需要一种方法让它理想地成为一个字符串或一个 int。有没有办法快速将颜色传递给修饰符?
struct Insight: Identifiable
let id = UUID()
let title: String
let description: String
let statusColor: Color
let header: String
let red: Color = Color(.red)
let yellow: Color = Color(.yellow)
let green: Color = Color(.green)
struct InsightList
static let topTenInsights = [
Insight(title: "Some text",
statusColor: red,
header: "Header"),
Finsight(title: "Some text",
statusColor: red,
header: "Income")
]
var insights: [insight] = insightList.topTenInsights
struct Landing: View
let user = Auth.auth().currentUser
let red: Color = Color(.red)
let yellow: Color = Color(.yellow)
let green: Color = Color(.green)
var body: some View
List(insights, id: \.id) userinsight in
HStack
Image(systemName: "circle.fill").foregroundStyle(insight.statusColor)
.scaledToFit()
.padding()
.shadow(radius: 0.9)
VStack(alignment: .leading, spacing: 8)
Text("Category: \(insight.header)")
.fontWeight(.semibold)
.lineLimit(2)
.minimumScaleFactor(0.5)
Text(insight.title)
.fontWeight(.light)
.lineLimit(2)
.minimumScaleFactor(0.9)
.padding(13)
.shadow(radius: 0.3)
【问题讨论】:
【参考方案1】:你可以做这样简单的事情:
func getStatusColor(_ status: Int) -> Color
switch status
case 0: return Color.red
case 1: return Color.yellow
case 2: return Color.green
default: return Color.blue
Image(systemName: "circle.fill")
.foregroundStyle(getStatusColor(statusValue))
.....
【讨论】:
非常感谢这个作品以上是关于在 Swift 中根据 API 调用设置前景色的主要内容,如果未能解决你的问题,请参考以下文章