Skip to content

Instantly share code, notes, and snippets.

@shaps80
Created June 9, 2021 20:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaps80/83205502733eef06abebeff91046d73d to your computer and use it in GitHub Desktop.
Save shaps80/83205502733eef06abebeff91046d73d to your computer and use it in GitHub Desktop.
Adds ResultBuilder support to UIMenu to simplify creation
import SwiftUI
typealias Menu = UIMenu
typealias Action = UIAction
@resultBuilder
struct MenuElementBuilder {
static func buildBlock(_ components: UIMenuElement...) -> [UIMenuElement] { components }
}
extension UIMenu {
convenience init(_ title: String = "", systemImage name: String? = nil, attributes: Options = [], @MenuElementBuilder _ elements: () -> [UIMenuElement]) {
self.init(
title: title,
image: name.flatMap { UIImage(named: $0) },
identifier: Identifier(title),
options: attributes,
children: elements()
)
}
}
extension UIAction {
convenience init(_ title: String, discoverabilityTitle: String? = nil, systemImage name: String? = nil, attributes: UIMenuElement.Attributes = [], _ action: @escaping () -> Void) {
self.init(
title: title,
image: name.flatMap { UIImage(named: $0) },
identifier: Identifier(title),
discoverabilityTitle: discoverabilityTitle,
attributes: attributes,
state: .off) { _ in action() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment