【问题标题】:How to show Text depends on switch case in SwiftUI?如何显示文本取决于 SwiftUI 中的 switch case?
【发布时间】:2021-10-30 19:49:34
【问题描述】:

我正在使用 SwiftUI,我有一个开关盒功能,取决于我想显示差异颜色和文本的开关盒。

    func status(status: Status){
            switch status {
            case .accepted:
//text "accepted"
                //green text   
    
            case .standby:
//text "standby"
                //yellow text
    
            case .notAllowed:
//text "notAllowed"
                 //red text
            }
        }

VStack(alignment: .leading) {
            Text("Test")
}

【问题讨论】:

    标签: ios swift swiftui switch-statement


    【解决方案1】:

    您可以在视图主体内简单地切换status,并在每个`case 内将正确的StringforegroundColor 分配给您的Text

    struct StatusView: View {
        let status: Status
    
        var body: some View {
            switch status {
            case .accepted:
                Text("accepted")
                    .foregroundColor(.green)
            case .standby:
                Text("standby")
                    .foregroundColor(.yellow)
            case .notAllowed:
                Text("not allowed")
                    .foregroundColor(.red)
            }
        }
    }
    

    或者如果你可以修改Status,你可以简单地为它分配一个StringrawValue,然后根据它的值显示适当的文本就更容易了。

    enum Status: String {
        case accepted
        case standby
        case notAllowed
    }
    
    struct StatusView: View {
        let status: Status
    
        var body: some View {
            Text(status.rawValue)
                .foregroundColor(statusColor(status: status))
        }
    
        private func statusColor(status: Status) -> Color {
            switch status {
            case .accepted:
                return .green
            case .standby:
                return .yellow
            case .notAllowed:
                return .red
            }
        }
    }
    

    【讨论】:

    • 谢谢你的回答..它完美..很抱歉问更多......但是如果我有基于条件的差异文本,你能修改答案..我修改了问题
    • @DávidPásztor:您的答案中不再需要VStack
    • @swiftPunk 很好,这是复制 OP 代码的遗留物
    【解决方案2】:

    这是基于 David 答案的更新和重构答案,这样您就不再需要 ststusColor 函数,您可以在任何地方访问 colorValue在您的项目中,而不是只能在 StatusView 内部访问的最后一个答案。

    struct StatusView: View {
        
        let status: Status
        
        var body: some View {
            
            Text(status.rawValue)
                .foregroundColor(status.colorValue)
            
        }
        
    }
    
    
    enum Status: String {
        
        case accepted
        case standby
        case notAllowed
        
        var colorValue: Color {
            switch self {
            case .accepted:
                return .green
            case .standby:
                return .yellow
            case .notAllowed:
                return .red
            }
        }
        
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-21
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-05-11
      相关资源
      最近更新 更多