如何更改嵌入 UIAction 中的基于 SF Symbols 的 UIButton 的颜色?

问题描述 投票:0回答:2

我正在使用以下代码生成一个按钮,但无法成功更改按钮的前景色。

let button = UIButton(
    type: .close,
    primaryAction: UIAction(
        image: UIImage(systemName: "x.circle"),
        handler: { _ in }
    )
)

我已经尝试过了

  • UIImage(systemName: "x.circle")?.withTintColor(.red)

  • UIImage(systemName: "x.circle")?.withTintColor(.systemRed, renderingMode: .alwaysOriginal)

  • button.setTitleColor(.systemRed, for: .normal)

  • 添加配置:

    var config = UIButton.Configuration.borderless()
    config.baseForegroundColor = .systemRed
    button.configuration = config
    
  • 使用不同的符号变体,例如:

    UIImage(systemName: "x.circle.fill")

在这个特定场景中,我只想更改图像的圆形背景区域的颜色,而不是 X(十字)或按钮的背景。本质上我想要一个带有灰色 X(十字)的红色填充圆圈。

所以我可以得到这个:

但我想要更像这样的东西(红色仅限于圆圈内):

uibutton uikit uiimage sf-symbols uiaction
2个回答
2
投票
  1. 将类型从

    .close
    更改为
    .custom

  2. UIImage(systemName: "x.circle")
    更改为

    UIImage(systemName: "x.circle")?.withTintColor(.systemRed, renderingMode: .alwaysOriginal)


0
投票

这两者都有效:

yourButton.showsMenuAsPrimaryAction = true
var elements: [UIMenuElement] = yourData.map({ item in
    
    let conf = UIImage.SymbolConfiguration(
                  paletteColors: [item.color]
               ).applying(UIImage.SymbolConfiguration(
                  pointSize: 40,
                  weight: .heavy)
               )
    
    let acn = UIAction(
        title: item.name,
        image: UIImage(
               systemName: "map",
               withConfiguration: conf)
    ) { [weak self] _ in
        guard let self else { return }
        yourButtonProcess(item.code)
    }
    return acn
})
yourButton.menu = UIMenu(children: elements)

yourButton.showsMenuAsPrimaryAction = true
var elements: [UIMenuElement] = yourData.map({ item in
    
    let acn = UIAction(
        title: item.name,
        image: UIImage(
            systemName: "map")?
            .withTintColor(
               item.color,
               renderingMode: .alwaysOriginal) // don't forget
    ) { [weak self] _ in
        guard let self else { return }
        yourButtonProcess(item.code)
    }
    return acn
})
yourButton.menu = UIMenu(children: elements)

就这样吧。

© www.soinside.com 2019 - 2024. All rights reserved.