Created
August 24, 2022 01:14
-
-
Save WillBishop/027a739736dac1ea12a0c6f3a1012a28 to your computer and use it in GitHub Desktop.
Change UIAction state without dismissing menu in iOS 16
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
//Bit of a crude example but it all works | |
var menu: UIMenu! | |
var selected = false | |
let toggleSelectionHandler: (UIAction) -> Void = { action in | |
selected.toggle() | |
// Actions are immutable once they're a child of a UIMenu, so we must create a copy before we modify anything | |
let replacementAction = action.copy() as! UIAction | |
if selected { | |
replacementAction.state = .on | |
} else { | |
replacementAction.state = .off | |
} | |
button.menu = menu.replacingChildren([replacementAction]) | |
} | |
let toggleSelection = UIAction(title: "Toggle", image: UIImage(systemName: "circle"), attributes: .keepsMenuPresented, handler: toggleSelectionHandler) | |
menu = UIMenu(title: "Test", children: [toggleSelection]) | |
//I have a button I'm assigning this to, but you an use the menu however you like | |
button.menu = menu | |
button.showsMenuAsPrimaryAction = true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment