How to show pull down button menu in IOS 14 swift

Viewed 2555

I created a pull down button like below

@IBOutlet weak var pullDownButton: UIButton!

Then I called a method from viewDidLoad() to configure pull down menu reference

func setupMenu() {
    let add = UIAction(title: "Add", image: UIImage(systemName: "plus")) { _ in
        self.showToast(message: "Add", seconds: 1.0)
    }
    
    let edit = UIAction(title: "Edit", image: UIImage(systemName: "pencil")) { _ in
        self.showToast(message: "Edit", seconds: 1.0)
    }
    
    let delete = UIAction(title: "Delete", image: UIImage(systemName: "minus")) { _ in
        self.showToast(message: "Delete", seconds: 1.0)
    }
    
    let menu = UIMenu(title: "Menu", children: [add, edit, delete])
    pullDownButton.menu = menu
    pullDownButton.showsMenuAsPrimaryAction = true
}

But I am unable to show the pull down menu upon long press or simple press.

Is there any way to show the pull down menu

3 Answers

Normal Button Declaration

@IBOutlet weak var btnAllocationType: UIButton!

use of this button

  let menuClosure = {(action: UIAction) in
            
        self.update(number: action.title)
    }
    btnAllocationType.menu = UIMenu(children: [
            UIAction(title: "option 1", state: .on, handler: 
                                menuClosure),
            UIAction(title: "option 2", handler: menuClosure),
            UIAction(title: "option 3", handler: menuClosure),
        ])
    btnAllocationType.showsMenuAsPrimaryAction = true
    btnAllocationType.changesSelectionAsPrimaryAction = true

and update function,where you get the selection

 func update(number:String) {
    if number == "option 1" {
        print("option 1 selected")
   
}

showButton.showsMenuAsPrimaryAction = true

Declare the IBOutlet for the button:

   @IBOutlet weak var filterPullDownButtom: UIButton!

Create a menu and add UIAction for each item:

   override func viewDidLoad() {
    
   super.viewDidLoad()
    filterPullDownButtom.showsMenuAsPrimaryAction = true
    filterPullDownButtom.changesSelectionAsPrimaryAction = true
    
    let optionClosure = {(action: UIAction) in
        
        if (action.index(ofAccessibilityElement: Any))
    }
    
    filterPullDownButtom.menu = UIMenu(children: [
        UIAction(title: "Within 10 kms", state: .on, handler: optionClosure),
        UIAction(title: "10 <= 20 kms", handler: optionClosure),
        UIAction(title: "20 <= 50 kms", handler: optionClosure),
        UIAction(title: "Within 100 Kms", handler: optionClosure),
    ])
Related