Search code examples
iosimageuibuttoniconstitle

UIButton title won't highlight when an image / background image is set


I have a custom button with a right-aligned arrow icon. Login button default

When it's highlighted with a tap, only the arrow icon is highlighted. The text remains white instead of turning gray like the icon does.

Login button highlighted

This is the code (scoped in a subclass of 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)

I've also overridden the backgroundRect property.

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)
}

I've also tried setting the button image (i.e. setImage(rightIcon, .normal)) instead of setting the button background image, but it didn't work.

I've also tried setting the highlight color for the icon and the title to gray, but that didn't work either.

I want both the text and the icon to be highlighted when the button is tapped, but I can't seem to find a way of achieving this. Is it genuinely impossible to do?


Solution

  • Setting the button type to System instead of Custom solved the issue. Now they both highlight like they should.

    IB Attribute inspector