设置图像/背景图像时,UIButton 标题不会突出显示

Ton*_*čić 2 icons image title uibutton ios

我有一个带有右对齐箭头图标的自定义按钮。 默认登录按钮

当它通过点击突出显示时,只有箭头图标突出显示。文本保持白色,而不是像图标那样变成灰色。

登录按钮突出显示

这是代码(作用域在 UIButton 的子类中):

let rightIcon = #imageLiteral(resourceName: "disclosureIndicator")

setTitleColor(.white, for: .normal)
setBackgroundImage(rightIcon, for: .normal)

guard let image = backgroundImage(for: .normal) else { return }

titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: image.size.width)
Run Code Online (Sandbox Code Playgroud)

我还覆盖了 backgroundRect 属性。

override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
    guard let image = backgroundImage(for: .normal) else {
        return super.backgroundRect(forBounds: bounds)
    }
    return CGRect(
        x: frame.width - (image.size.width + 20),
        y: (frame.height / 4) + (image.size.height / 4),
        width: image.size.width,
        height: image.size.height)
}
Run Code Online (Sandbox Code Playgroud)

我也试过设置按钮图像(即setImage(rightIcon, .normal))而不是设置按钮背景图像,但它没有用。

我还尝试将图标的突出显示颜色和标题设置为灰色,但这也不起作用。

我希望在点击按钮时突出显示文本和图标,但我似乎找不到实现此目的的方法。真的不可能做到吗?

Ton*_*čić 6

将按钮类型设置为System而不是Custom解决了问题。现在他们都像他们应该的那样突出显示。

IB 属性检查器