如何创建带有弹出按钮(或下拉按钮)的交互式菜单

问题描述 投票:0回答:2

我正在尝试在我的 Swift 应用程序中创建一个上下文菜单,但菜单项是交互式的,即来自数据库。

例如,我有一个包含国家/地区的数组。有时这个数组可以包含 5 个项目,其他时候可以包含 6 个项目,依此类推...我尝试使用这些项目创建一个菜单,但我不能。我想我对此还太新了。

我的代码是这样的:

override func viewDidLoad() {
        super.viewDidLoad()

setPopUpButton()

}


func setPopUpButton(){

        // Here are my Array with countries name. It's works fine.
        let statesOf = ArrayWithCountries()
        
        let optionClosure = {(action: UIAction) in
            print(action.title)
        }
       
        // In this part I want to fetch the countries array. Now it's a static menu!
        popUpButtonStates.menu = UIMenu(children: [
            UIAction(title: "Country 1", state: .off, handler: optionClosure),
            UIAction(title: "Country 2", state: .on, handler: optionClosure),
            UIAction(title: "Country 3", state: .off, handler: optionClosure),
            UIAction(title: "Country 4", state: .off , handler: optionClosure)
        ])
        
        popUpButtonStates.showsMenuAsPrimaryAction = true
        popUpButtonStates.changesSelectionAsPrimaryAction = true
        
    }

我尝试过使用 for 循环。像这样的东西:

for country in countries{
UIAction(title: country, state: .off, handler: optionClosure)
}

但是这个解决方案不起作用。

对此有一些帮助吗?谢谢!

swift popup
2个回答
5
投票

我不确定你的“国家”数组是什么样子,但假设它只是一个包含国家/地区的列表:

// create the closure        
let optionClosure = {(action: UIAction) in
            print(action.title)
        }

// create an array to store the actions
var optionsArray = [UIAction]()

// loop and populate the actions array            
for country in countries{
    // create each action and insert the right country as a title
    let action = UIAction(title: country, state: .off, handler: optionClosure)
            
    // add newly created action to actions array        
    optionsArray.append(action)
}
        
        
// set the state of first country in the array as ON
optionsArray[0].state = .on

// create an options menu        
let optionsMenu = UIMenu(title: "", options: .displayInline, children: optionsArray)
        
// add everything to your button        
popUpButtonStates.menu = optionsMenu

// make sure the popup button shows the selected value
popUpButtonStates.changesSelectionAsPrimaryAction = true
popUpButtonStates.showsMenuAsPrimaryAction = true

        

0
投票

2024 年语法更简单......

yourButton.menu = UIMenu(children: strings.map({ s in
    return UIAction(title: s) { [weak self] _ in
        print("user selected \(s)")
    }
})
)
© www.soinside.com 2019 - 2024. All rights reserved.