Skip to content

Instantly share code, notes, and snippets.

@francescoleoni98
Last active June 29, 2023 12:59
Show Gist options
  • Save francescoleoni98/9ec227a73ccccfa6a3ad85d2c0fdcf66 to your computer and use it in GitHub Desktop.
Save francescoleoni98/9ec227a73ccccfa6a3ad85d2c0fdcf66 to your computer and use it in GitHub Desktop.
Menu palettes for swiftUI and UIKit
// SwiftUI
struct PaletteView: View {
enum Tag: CaseIterable {
case red, orange, yellow, green, blue, purple
var color: Color {
switch self {
case .red: .red
case .orange: .orange
case .yellow: .yellow
case .green: .green
case .blue: .blue
case .purple: .purple
}
}
}
@State private var selection: Tag = .red
var body: some View {
NavigationView {
VStack {
}
.navigationTitle("Palette menu")
.toolbar {
Menu("Options") {
Button("Remove tag") { }
Picker("Tags", selection: $selection) {
ForEach(Tag.allCases, id: \.self) { tag in
Image(systemName: selection == tag ? "circle.slash.fill" : "circle.fill")
.tint(tag.color)
.tag(tag)
}
}
.pickerStyle(.palette)
.paletteSelectionEffect(.custom)
}
}
}
}
}
// UIKit
class PaletteViewController: UIViewController {
enum Tag: CaseIterable {
case red, orange, yellow, green, blue, purple
var color: UIColor {
switch self {
case .red: .red
case .orange: .orange
case .yellow: .yellow
case .green: .green
case .blue: .blue
case .purple: .purple
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let tagOptions = Tag.allCases.map { tag in
let image = UIImage(systemName: "circle.fill")?.withTintColor(tag.color, renderingMode: .alwaysOriginal)
return UIAction(image: image) { _ in }
}
let tagMenu = UIMenu(options: [.displayInline, .displayAsPalette], children: tagOptions)
let menu = UIMenu(children: [
UIAction(title: "Remove tag") { _ in },
tagMenu
])
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Options", menu: menu)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment