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

如何手动修改UIMenu中选中的UIAction以保留筛选器选中状态

解决方案

核心逻辑是通过手动管理UIAction的state属性控制菜单项的勾选状态,同时保存选中值同步更新按钮文本,具体修改步骤如下:

步骤1:给筛选页新增接收选中值的属性

在FiltersVC中定义外部可传入的选中参数,用于接收上次筛选的结果:

// 空间类型选中值,默认是All
var selectedSpaceType: String = "All"
// 可按相同规则新增site、duration等其他筛选条件的接收属性

步骤2:改造菜单项生成逻辑,自动匹配选中状态

修改spaceTypeMenuItems的实现,遍历所有选项时和当前选中值匹配,对应项的state设为.on(显示勾选),同时在选中回调中同步更新选中值和按钮文本:

private var spaceTypeMenuItems: [UIAction] {
    let items = [
        UIAction(title: "All", handler: { [weak self] action in
            self?.updateSpaceTypeSelection(title: action.title)
        }),
        UIAction(title: "Meeting Room", handler: { [weak self] action in
            self?.updateSpaceTypeSelection(title: action.title)
        }),
        UIAction(title: "Desk", handler: { [weak self] action in
            self?.updateSpaceTypeSelection(title: action.title)
        }),
        UIAction(title: "Boardroom", handler: { [weak self] action in
            self?.updateSpaceTypeSelection(title: action.title)
        })
    ]
    // 自动匹配当前选中项,设置勾选状态
    return items.map { action in
        action.state = action.title == selectedSpaceType ? .on : .off
        return action
    }
}

// 抽取出公共的选中更新方法,避免重复代码
private func updateSpaceTypeSelection(title: String) {
    selectedSpaceType = title
    spaceTypeButton?.setTitle(title, for: .normal)
    // 重新赋值menu刷新勾选状态
    spaceTypeButton?.menu = spaceTypeMenu
}

步骤3:页面显示时初始化按钮文本

在viewWillAppear中给按钮设置初始选中的文本:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    spaceTypeButton?.setTitle(selectedSpaceType, for: .normal)
}

步骤4:改造按钮初始化配置

修改createSpaceTypeMenu方法,避免按钮选中后文本样式异常:

func createSpaceTypeMenu() {
    spaceTypeButton?.menu = spaceTypeMenu
    spaceTypeButton?.showsMenuAsPrimaryAction = true
    // 新增这行,防止点击后按钮文本自动变灰
    spaceTypeButton?.changesSelectionAsPrimaryAction = false
}

步骤5:主列表页打开筛选页时传入上次选中值

在主列表页跳转筛选页的逻辑中,把之前保存的筛选结果传入:

// 主列表页跳转示例
let filterVC = FiltersVC()
// 传入上次保存的空间类型选中值
filterVC.selectedSpaceType = currentSavedFilter.spaceType ?? "All"
// 按相同规则传入其他筛选参数
filterVC.applyFiltersCallback = { [weak self] filter in
    // 保存筛选结果,下次打开筛选页时复用
    self?.currentSavedFilter = filter
    // 刷新列表逻辑
}
present(filterVC, animated: true)

剩余的site、duration等绑定了UIMenu的按钮,按照完全相同的逻辑改造即可实现状态保存。

内容的提问来源于stack exchange,提问作者GameDev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:57:00