You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何设置UIButton弹出菜单的默认选中选项

如何设置UIButton菜单的默认选中项

你没法直接调用accountTypePopUpButton.menu的类似setIndex或setValue的方法来实现,但可以通过两步操作达成需求,且完全不改变选项展示顺序:

  1. 设置按钮默认显示标题
    直接给按钮设置默认标题为"option 3",覆盖默认的第一个选项标题:
accountTypePopUpButton.setTitle("option 3", for: .normal)
  1. 标记菜单中对应选项为选中状态(可选)
    如果需要菜单里的"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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 14:45:58