27

My UIButton instance is not highlighting when pressed. I'm pretty sure my code is correct. This only happens in this specific class that I am using. I'm guessing because the function has been overridden by a protocol that I am conforming to.

I want to make the UIButton highlight the default way, but I have to do it manually. How can I force highlight the button when pressed, and what are the default settings for it (in terms of colour), so that it is consistent with all the other buttons?

Here is my current code:

    let backButton = UIButton()
    backButton.setTitle("back", for: .normal)
    backButton.setTitleColor(UIColor.black, for: .normal)
    backButton.adjustsImageWhenHighlighted = true
    RevealBar.addSubview(backButton)
    backButton.snp.makeConstraints { (make) -> Void in
        make.center.equalTo(RevealBar)
        make.width.equalTo(RevealBar)
        make.height.equalTo(RevealBar)
    }

    backButton.addTarget(self, action: #selector(self.goBack), for: .touchUpInside)
shim
  • 9,289
  • 12
  • 69
  • 108
slimboy
  • 1,633
  • 2
  • 22
  • 45

2 Answers2

60

Initialize the button using UIButton(type buttonType: .system) instead of UIButton().

When you use the latter it won't properly set up button highlighting because the default button type is UIButtonType.custom, which is intended as a blank slate without any of the default styling or highlighting behaviour.

Note, from Apple's UIButton documentation:

A button’s type defines its basic appearance and behavior. You specify the type of a button at creation time using the init(type:) method or in your storyboard file. After creating a button, you cannot change its type. The most commonly used button types are the Custom and System types, but use the other types when appropriate.

shim
  • 9,289
  • 12
  • 69
  • 108
1

Your code is correct except this line let backButton = UIButton(). Here you need to say button Type. Either you can init with Frame or Button Type

Sivajee Battina
  • 4,124
  • 2
  • 22
  • 45
  • If you initialize using the frame initializer the type will still be custom and the button will not have the OP's desired default highlighting. – shim Dec 30 '16 at 21:38
  • And as I note in my [answer](http://stackoverflow.com/a/41401769/1032372) it is not possible to set the type after the button has been created (whereas it is possible to change the frame anytime). – shim Dec 30 '16 at 21:44