如何将视图修饰符分离为可调用/包含的结构

时间:2020-08-04 21:33:22

标签: swift swiftui

在某些情况下,整个视图都使用特定的视图修饰符。可以一遍又一遍地调用它,而不是一遍又一遍地重复此代码? .foreground修饰符本身没有上下文,因为它不是独立的语法.....

struct ColorTheme: View {
    
    @ObservedObject var userSettings = UserSettings()
    
    var body: some View {
        .foregroundColor( ((userSettings.mapType == "Satellite") ||  Error: Cannot infer contextual base in reference to member 'foregroundColor'
            (userSettings.mapType == "Hybrid") ||
            (userSettings.mapStyle == "AssassinsCreed") ||
            (userSettings.mapStyle == "Aubergine")  ||
            (userSettings.mapStyle == "Dark")  ||
            (userSettings.mapStyle == "MidnightCommand")  ||
            (userSettings.mapStyle == "Night")) ? Color(UIColor.white) : Color(UIColor.black))
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

class UserSettings: ObservableObject {
    @Published var mapType: String = "Satellite"
    
    var fgColor: Color {
        switch mapType {
        case "Satellite", "Hybrid", "AssassinsCreed", "Aubergine", "Dark", "MidnightCommand", "Night":
            return Color(UIColor.white)
        default:
            return Color(UIColor.black)
        }
    }
}

struct ColorTheme: View {
    
    @ObservedObject var userSettings = UserSettings()
    
    var body: some View {
        Text("test")
            .foregroundColor(userSettings.fgColor)
    }
}

您也可以考虑将mapType设为枚举


编辑

您可能正在寻找View扩展:

extension View {
    @ViewBuilder
    func customFgColor(mapType: String) -> some View {
        switch mapType {
        case "Satellite", "Hybrid", "AssassinsCreed", "Aubergine", "Dark", "MidnightCommand", "Night":
            return self.foregroundColor(Color(UIColor.white))
        default:
            return self.foregroundColor(Color(UIColor.black))
        }
    }
}

struct ColorTheme: View {
    @ObservedObject var userSettings = UserSettings()

    var body: some View {
        Text("test")
            .customFgColor(mapType: userSettings.mapType)
    }
}