SwiftUI中如何根据switch case的结果显示对应文本与颜色
SwiftUI 状态对应文本及颜色实现方案
你原有status方法无返回值,无法直接嵌入SwiftUI视图结构中使用,可参考以下任意一种方案修改:
方案1:直接返回对应样式的Text组件
enum Status { case accepted, standby, notAllowed } func statusText(for status: Status) -> Text { switch status { case .accepted: return Text("accepted") .foregroundColor(.green) case .standby: return Text("standby") .foregroundColor(.yellow) case .notAllowed: return Text("notAllowed") .foregroundColor(.red) } } // 视图调用示例 VStack(alignment: .leading) { Text("Test") // 替换参数为你实际持有的status变量即可 statusText(for: .accepted) }
方案2:给Status枚举加扩展(更符合SwiftUI风格)
extension Status { var displayText: String { switch self { case .accepted: return "accepted" case .standby: return "standby" case .notAllowed: return "notAllowed" } } var displayColor: Color { switch self { case .accepted: return .green case .standby: return .yellow case .notAllowed: return .red } } } // 视图调用示例 VStack(alignment: .leading) { Text("Test") Text(yourStatus.displayText) .foregroundColor(yourStatus.displayColor) }
方案3:返回文本+颜色元组(适合需要拆分使用的场景)
func statusInfo(for status: Status) -> (text: String, color: Color) { switch status { case .accepted: return ("accepted", .green) case .standby: return ("standby", .yellow) case .notAllowed: return ("notAllowed", .red) } } // 视图调用示例 VStack(alignment: .leading) { Text("Test") let info = statusInfo(for: .standby) Text(info.text) .foregroundColor(info.color) }
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

