我正在使用以下代码生成一个按钮,但无法成功更改按钮的前景色。
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(十字)的红色填充圆圈。
将类型从
.close
更改为 .custom
将
UIImage(systemName: "x.circle")
更改为
UIImage(systemName: "x.circle")?.withTintColor(.systemRed, renderingMode: .alwaysOriginal)
这两者都有效:
或
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)
就这样吧。