Skip to content

Instantly share code, notes, and snippets.

@lotusirous
Created December 1, 2022 07:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lotusirous/393321aebd2b1edec2bee89af8ea4ddb to your computer and use it in GitHub Desktop.
Save lotusirous/393321aebd2b1edec2bee89af8ea4ddb to your computer and use it in GitHub Desktop.
A elegant solution dropdown menu for SwiftUI
//
// ContentView.swift
// WeirdSheet
//
// Created by lotusirous on 28/11/2022.
//
import SwiftUI
protocol Nameable {
var name: String { get }
}
struct City: Nameable, Identifiable {
let id = UUID()
let name: String
let code: String
}
struct Dropdown<T>: View where T: Nameable & Identifiable {
let items: [T]
@Binding var value: T
var body: some View {
VStack {
Menu {
ForEach(items) { item in
Button {
self.value = item
} label: {
Text(item.name)
}
}
} label: {
HStack {
Text(value.name.isEmpty ? "Select city" : value.name)
Spacer()
Image(systemName: "chevron.down")
}
.padding()
.foregroundColor(.black)
.background(
RoundedRectangle(cornerRadius: 10).stroke(style: .init())
.foregroundColor(.gray)
)
}
}
.frame(width: .infinity)
}
}
struct ContentView: View {
var cities: [City] = [
City(name: "Paris", code: "paris"),
City(name: "London", code: "london")
]
@State var selectedCity: City = .init(name: "", code: "")
var body: some View {
VStack {
Dropdown(items: cities, value: $selectedCity)
Text("You have selected: \(selectedCity.name)")
}
.frame(maxWidth: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment