Kris2k
Kris2k

Reputation: 367

How to update UIMenu and UIContextMenuConfiguration dynamically in iOS?

I am having a UIAction called "Add to Favourites" in UIMenu and UIContextMenuConfiguration for Cells of a UITableView. I want to change the menu the next time it is shown as "Remove from Favourites". But, I learnt that UIMenu is immutable.

How can I achieve my goal to update the menu dynamically ?

Upvotes: 2

Views: 485

Answers (1)

jki
jki

Reputation: 4826

@objc extension UIMenu {
    
    /// Recalculates menu on every appearance (e.g. when assigning to UIButtons as primary action)
    static func lazyMenu(builder: @escaping () -> UIMenu) -> UIMenu {
        return UIMenu(children: [
                // rebuild menu every time menu is accessed
                UIDeferredMenuElement.uncached { completion in
                    let menu = builder()
                    completion([menu])
                }
            ])
    }
}

Make sure that returned menu from your builder block includes .displayInline: e.g.

UIMenu(options: .displayInline, children: myMenuItems) 

Upvotes: 2

Related Questions