Created
July 10, 2020 23:12
-
-
Save analogpotato/c47794e9a6a7f12a51b71bf3bee6b3cf to your computer and use it in GitHub Desktop.
Using UIViewRepresentable to declare a UIKit Menu from a button
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//In your view, declare a UIViewRepresentable as a UIButton type as seen below. | |
//This is important as you cannot do it as a UIBarButtonItem (at least as I've found in Xcode 12 beta 2). | |
struct MenuButtonView: UIViewRepresentable { | |
typealias UIViewType = UIButton | |
let saveAction = UIAction(title: "") { action in } | |
let saveMenu = UIMenu(title: "", children: [ | |
UIAction(title: "First Menu Item", image: UIImage(systemName: "nameOfSFSymbol")) { action in | |
//code action for menu item | |
}, | |
UIAction(title: "First Menu Item", image: UIImage(systemName: "nameOfSFSymbol")) { action in | |
//code action for menu item | |
}, | |
UIAction(title: "First Menu Item", image: UIImage(systemName: "nameOfSFSymbol")) { action in | |
//code action for menu item | |
}, | |
]) | |
func makeUIView(context: Context) -> UIButton { | |
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) | |
button.showsMenuAsPrimaryAction = true | |
button.menu = saveMenu | |
return button | |
} | |
func updateUIView(_ uiView: UIButton, context: Context) { | |
uiView.setImage(UIImage(systemName: "plus"), for: .normal) | |
} | |
} | |
// Once you have declared a UIViewRepresentable, it works just like a SwiftUI view and thus can be declared anywhere you would need that view. | |
//Declare it as MenuButtonView() | |
//In a toolbar you can declare it as follows: | |
.toolbar { | |
ToolbarItem(placement: .navigationBarTrailing) { | |
HStack { | |
SaveButtonView() | |
} | |
} | |
} | |
//The only issue I have found is in placing any code in the actions of the button, I can't seem to figure out how to get it to push to another view if it's in Swift UI. | |
//If you find out how to push to another SwiftUI view, let me know! It's been stumping me for awhile! | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Below are two types of navigation, which are activated by the menu.
ContentView_Sheet
presents the new view as a sheet, andContentView_NavigationLink
pushes the new view onto the navigation stack.ContentView_NavigationLink
feels a little hacky because a hiddenNavigationLink
is used to get around a crash that occurs when aNavigationLink
is embedded in aNavigationView
'snavigationBarItems
.