Swift中如何设置UIButton弹出菜单的默认选中选项
你没法直接调用accountTypePopUpButton.menu的类似setIndex或setValue的方法来实现,但可以通过两步操作达成需求,且完全不改变选项展示顺序:
- 设置按钮默认显示标题
直接给按钮设置默认标题为"option 3",覆盖默认的第一个选项标题:
accountTypePopUpButton.setTitle("option 3", for: .normal)
- 标记菜单中对应选项为选中状态(可选)
如果需要菜单里的"option 3"默认显示选中样式(比如勾选标记),可以在创建UIAction时单独设置它的状态为.on:
// 先单独创建每个Action,方便修改第三个的状态 let option1 = UIAction(title: "option 1", handler: optionClosure) let option2 = UIAction(title: "option 2", handler: optionClosure) let option3 = UIAction(title: "option 3", handler: optionClosure) option3.state = .on // 设置为选中状态 let option4 = UIAction(title: "option 4", handler: optionClosure) accountTypePopUpButton.menu = UIMenu(children: [option1, option2, option3, option4]) accountTypePopUpButton.showsMenuAsPrimaryAction = true
如果希望点击其他选项后,按钮标题自动同步为选中选项的标题,可以在处理闭包里补充逻辑:
let optionClosure: UIActionHandler = { [weak self] selectedAction in guard let self = self else { return } // 更新按钮标题 self.accountTypePopUpButton.setTitle(selectedAction.title, for: .normal) // 同步菜单中选项的选中状态 self.accountTypePopUpButton.menu?.children.forEach { guard let action = $0 as? UIAction else { return } action.state = action == selectedAction ? .on : .off } }
内容的提问来源于stack exchange,提问作者fabiobh
相关产品推荐
相关产品推荐

