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

时间:2018-01-10 09:44:38

标签: ios image uibutton icons title

我有一个带有右对齐箭头图标的自定义按钮。 Login button default

点击时突出显示,只突出显示箭头图标。文字保持白色而不是像图标一样变灰。

Login button highlighted

这是代码(在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)

我还覆盖了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)
}

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

我也尝试将图标的高亮颜色和标题设置为灰色,但这也不起作用。

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

1 个答案:

答案 0 :(得分:3)

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

IB Attribute inspector