-2

For my buttons that I create through the storyboard, when they are clicked they become slightly darker as if there is a shadow on them - the typical behavior when buttons are pressed. However, when I create buttons programmatically, they don't do this - is there a property I can change so that they will darken when selected, like the storyboard buttons do? PS. I don't mean showsTouchWhenHighlighted — this has another animation, but I am looking for the same animation that storyboard buttons have.

fisch
  • 136
  • 7

1 Answers1

1

UIButtons have a bunch of methods of the form:

func setXXX(_ XXX: type, 
          for state: UIControl.State)

Where XXX are all the things one might care about affecting button's look (title, titleColor, backgroundImage, etc).

The control state describes all the states the button can be in before, during and after user interaction. The states you probably care about most are highlighted and selected.

Interactions of the states can get a little tricky because you need to fully specify the state you're trying to setup the UI for. See a good explanation of that here.

danh
  • 62,181
  • 10
  • 95
  • 136
  • How would you change the background color? I don't see a function for that, I tried changing it for .touchDown and reverting it for .touchUpInside and .touchUpOutside but then there's a weird glitch where if you scroll it will call the touchdown func but not one of the other two to revert it. – fisch Jun 10 '20 at 02:23
  • The proper way is two background images, one each set for the highlighted state. This also can be done in code. https://stackoverflow.com/a/14525049/294949 – danh Jun 10 '20 at 04:50