Skip to content

Instantly share code, notes, and snippets.

@imthath-m
Created July 23, 2020 17:51
Show Gist options
  • Save imthath-m/207f6ab91795839fa4890e24ef12a422 to your computer and use it in GitHub Desktop.
Save imthath-m/207f6ab91795839fa4890e24ef12a422 to your computer and use it in GitHub Desktop.
@available(iOS 14.0, *)
public struct EnumMenuPicker<T: Hashable & CaseIterable, V: View>: View {
@Binding var selected: T
var title: String? = nil
let mapping: (T) -> V
public var body: some View {
if let existingTitle = title {
HStack {
Text(existingTitle)
.foregroundColor(.primary)
Spacer()
menu
}
} else {
menu
}
}
var menu: some View {
Menu(content: {
ForEach(Array(T.allCases), id: \.self) { item in
Button(action: {
selected = item
}, label: {
view(for: item)
})
}
}, label: {
mapping(selected)
})
}
@ViewBuilder func view(for item: T) -> some View {
if selected == item {
HStack {
Image(systemSymbol: .checkmark)
self.mapping(item)
}
} else {
self.mapping(item)
}
}
}
@Rashesh-Bosamiya
Copy link

Rashesh-Bosamiya commented Jan 6, 2021

Could you please add an example code snippet on how to make use of this class?

I have following enum in my project.

enum VideoQuality: CaseIterable {
    case noChange
    case low
    case medium
    case high
    
    var name: String {
        switch self {
        case .noChange:
            return "Same as source"
        case .low:
            return "Low"
        case .high:
            return "High"
        case .medium:
            return "Medium"
        }
    }
    
    var value: String {
        switch self {
        case .noChange:
            return AVAssetExportPresetPassthrough
        case .low:
            return AVAssetExportPresetLowQuality
        case .high:
            return AVAssetExportPresetHighestQuality
        case .medium:
            return AVAssetExportPresetMediumQuality
        }
    }
}

Can you please provide a code snippet on how to use this enum into your class?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment