Tim
Tim

Reputation: 737

How to separate out view modifiers into callable/includable structs

I have a case where a particular view modifier is used throughout a view. Instead of repeating this code over and over again, is it possible to make it callable? The .foreground modifier has no context by itself as it is not standalone syntax.....

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))
    }
}

Upvotes: 0

Views: 60

Answers (1)

pawello2222
pawello2222

Reputation: 54506

You may try the following:

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)
    }
}

You may also consider making mapType an enum.


EDIT

You may be looking for a View extension:

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)
    }
}

Upvotes: 1

Related Questions