如何通过UIButton.Configuration配置带自定义SFSymbol且标题随菜单变化的按钮?
解决方案
1. 替换默认菜单图标
要替换按钮默认的chevron.up.chevron.down图标,只需在创建UIButton.Configuration时指定自定义SFSymbol,并调整图标布局:
- 用
UIImage(systemName:)加载目标图标(例:chevron.down) - 通过
imagePlacement控制图标位置(如放在标题右侧) - 可选设置
imagePadding调整图标与标题的间距
2. 实现标题随选中项动态更新
让按钮标题跟随菜单选项变化,需要:
- 初始化按钮时设置默认标题(对应初始选中的菜单选项)
- 在
UIAction的回调中,更新按钮的configuration.title为当前选中的选项标题 - 为
UIAction设置选中状态,配合菜单的.singleSelection选项,确保选中项显示对勾标记
修改后的完整代码
private let sortButton: UIButton = { var buttonConfig = UIButton.Configuration.plain() // 设置自定义SFSymbol图标 buttonConfig.image = UIImage(systemName: "chevron.down") // 图标置于标题右侧 buttonConfig.imagePlacement = .trailing // 图标与标题的间距 buttonConfig.imagePadding = 4 // 设置默认标题(对应初始选中项) buttonConfig.title = "New" let button = UIButton(configuration: buttonConfig) button.tintColor = R.color.controlSecondaryTypo() button.showsMenuAsPrimaryAction = true button.changesSelectionAsPrimaryAction = true return button }() private func setupButton() { let items = ["New", "Old"] let actions: [UIAction] = items.enumerated().map { index, title in // 给第一个选项设置初始选中状态 let state: UIAction.State = index == 0 ? .on : .off let action = UIAction(title: title, state: state) { [weak self] action in // 更新按钮标题为当前选中项的标题 var updatedConfig = self?.sortButton.configuration updatedConfig?.title = action.title self?.sortButton.configuration = updatedConfig } return action } let menu = UIMenu(options: .singleSelection, children: actions) sortButton.menu = menu }
关键细节说明
- 用
enumerated()遍历选项,给初始选中项设置.on状态,配合.singleSelection确保菜单仅一个选项处于选中状态 - 由于
UIButton.Configuration是值类型,修改时需先复制当前配置,修改后重新赋值给按钮 - 图标位置可通过
imagePlacement调整为.leading(左侧)或.trailing(右侧),按需选择
内容的提问来源于stack exchange,提问作者VladSedenkov
相关产品推荐
相关产品推荐

