ios 如何通过UIButton配置按钮,使用自定义SFSymbol配置?

yhxst69z  于 2023-07-01  发布在  iOS
关注(0)|答案(2)|浏览(157)

我创建我的按钮:

private let sortButton: UIButton = {
        let buttonConfig = UIButton.Configuration.plain()
        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.map {
            let action = UIAction(title: $0) { action in
                print("\(action.title)")
            }

            return action
        }

        let menu = UIMenu(options: .singleSelection, children: actions)
        sortButton.menu = menu
    }

这里是我的按钮enter image description here的显示
默认情况下,它始终显示为chevron.up.chevron.down。如何更改为其他SFSymbol?示例:chevron.down
我希望能够配置按钮,将根据所选的UIMenu与自定义SFSymbol元素更改标题

zrfyljdw

zrfyljdw1#

当您使用菜单设置UIButton并启用showsMenuAsPrimaryActionchangesSelectionAsPrimaryAction两个属性时,该按钮将自动显示chevron.up.chevron.down指示符,以指示这是一个弹出按钮。
UIButton.Configuration有一个indicator属性,当您将按钮设置为弹出按钮时,该属性默认为.popup
因为这是一个标准,你应该考虑让图标保持原样,因为用户会认出它是什么。
但是如果你确实想改变图标,你将需要应用你自己的按钮图像并删除指示器。
将按钮配置代码更改为:

var buttonConfig = UIButton.Configuration.plain()
buttonConfig.indicator = .none // Hide the standard popup icon
buttonConfig.image = UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(scale: .small)) // Use the new icon
buttonConfig.imagePlacement = .trailing // Put the image after the title
kognpnkq

kognpnkq2#

这是因为UIButton.Configuration.plain(),在目前的实现中,我没有看到任何理由通过配置初始化按钮,你可以按钮()和后添加你的菜单。
但是如果你需要配置,那么使用.borderless(),那个配置可能就是你要找的。
或者通过扩展来创建自己的配置,并使用它的设置。
顺便说一句,如果你的愿望需要.plain(),你可以做一些黑客的东西😅😬,比如:

sortButton.subviews.first(where: { $0 is UIImageView })?.isHidden = true

但我认为简单的Button()或.borderless()就足够了

相关问题