Tusker/Tusker/Views/MenuPicker.swift

59 lines
1.6 KiB
Swift
Raw Normal View History

//
// MenuPicker.swift
// Tusker
//
// Created by Shadowfacts on 11/7/22.
// Copyright © 2022 Shadowfacts. All rights reserved.
//
import SwiftUI
struct MenuPicker<Value: Hashable>: View {
@Binding var selection: Value
let options: [Option]
private var selectedOption: Option {
options.first(where: { $0.value == selection })!
}
var body: some View {
Menu {
ForEach(options, id: \.value) { option in
Button {
selection = option.value
} label: {
Label(option.title, systemImage: selection == option.value ? "checkmark" : "")
}
}
} label: {
// zstack so that the size of the picker is the size of the largest option
ZStack {
ForEach(options, id: \.value) { option in
HStack {
Text(option.title)
Image(systemName: "chevron.up.chevron.down")
}
.opacity(option.value == selection ? 1 : 0)
}
}
}
.menuStyle(.borderlessButton)
}
struct Option {
let title: String
let value: Value
}
}
struct MenuPicker_Previews: PreviewProvider {
@State static var value = 0
static var previews: some View {
MenuPicker(selection: $value, options: [
.init(title: "Zero", value: 0),
.init(title: "One", value: 1),
.init(title: "Two", value: 2),
])
}
}