UIMenu二次选择选项时值未更新,如何修复该问题?
问题现象
你的代码实现了一个带5个选项的UIMenu,用户首次选择非默认选项("Selecione a chave")后,菜单会切换为4个选项,但后续再次选择新选项时,accountType的值不会发生变化。
问题根源
替换菜单时,新创建的UIAction使用了空的handler: { _ in },没有绑定原来的optionClosure,导致后续选择操作无法触发更新accountType的逻辑。
修复代码
fileprivate func configMenu() { let optionClosure = { [weak self] (action: UIAction) in print("v000: \(action.title)") guard let self = self else { return } if action.title != "Selecione a chave" { // 仅在当前菜单包含默认选项时,才更新为4选项菜单 let hasDefaultOption = self.accountTypePopUpButton.menu?.children.contains(where: { ($0 as? UIAction)?.title == "Selecione a chave" }) == true if hasDefaultOption { let updatedActions = ["CPF/CNPJ", "Celular", "E-mail", "Chave aleatória"].map { title in UIAction(title: title, handler: optionClosure) } self.accountTypePopUpButton.menu = UIMenu(children: updatedActions) } self.accountTypeFilled = true self.accountType = action.title // 无需调用reloadInputViews,更新menu后按钮会自动刷新 } } let initialActions = [ UIAction(title: "Selecione a chave", handler: optionClosure), UIAction(title: "CPF/CNPJ", handler: optionClosure), UIAction(title: "Celular", handler: optionClosure), UIAction(title: "E-mail", handler: optionClosure), UIAction(title: "Chave aleatória", handler: optionClosure) ] accountTypePopUpButton.menu = UIMenu(children: initialActions) accountTypePopUpButton.showsMenuAsPrimaryAction = true accountTypePopUpButton.changesSelectionAsPrimaryAction = true }
关键改动说明
- 统一Handler绑定:新菜单的所有
UIAction都复用optionClosure作为处理闭包,确保每次选择都能触发accountType的更新逻辑。 - 避免重复更新菜单:增加判断逻辑,仅当当前菜单仍包含默认选项时才替换菜单,减少不必要的视图更新操作。
- 移除冗余调用:删除
reloadInputViews(),因为UIPopUpButton在menu属性更新后会自动刷新菜单内容。
内容的提问来源于stack exchange,提问作者fabiobh
相关产品推荐
相关产品推荐

