2

I am having a problem when adding a UIButton programatically. There is no "tap-animation".

Does anyone know why that occurs and how to fix this? I couldn't find anything on this topic...

let weiterButton: UIButton = {
    let v = UIButton()
    v.translatesAutoresizingMaskIntoConstraints = false
    v.setTitle("WEITER", for: .normal)
    v.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 20)
    v.titleLabel?.textColor = .white
    v.backgroundColor = UIColor(red: 75/255, green: 75/255, blue: 75/255, alpha: 1)
    v.addTarget(self, action: #selector(weiterButtonTapped), for: .touchUpInside)
    return v
}()

Animation I would like to have:

Animation

Chris
  • 1,828
  • 6
  • 40
  • 108
  • did u try applying colours for states highlighted / pressed ? – Teja Nandamuri Jan 20 '20 at 20:08
  • no. I just want the standard tap animation. It seems like it is working when adding a `backgroundImage` but I also want the animation without an `image` .. – Chris Jan 20 '20 at 20:16
  • @TejaNandamuri is right. You need to add custom colours of text for highlighted states, e.g. just add this line `v.setTitleColor(.red, for: .highlighted)` – AlexSmet Jan 20 '20 at 20:23
  • but `backgroundColor` should be changed and not `TitleColor`. – Chris Jan 20 '20 at 20:34
  • @AlexSmet I updated my question with a video – Chris Jan 20 '20 at 20:48
  • Does this answer your question? [How to change the background color of a UIButton while it's highlighted?](https://stackoverflow.com/questions/14523348/how-to-change-the-background-color-of-a-uibutton-while-its-highlighted) – koen Jan 20 '20 at 20:52
  • See https://stackoverflow.com/questions/14523348/how-to-change-the-background-color-of-a-uibutton-while-its-highlighted – AlexSmet Jan 20 '20 at 20:53
  • got it now, thanks :) – Chris Jan 20 '20 at 21:20

1 Answers1

2

You have to set lazy var instead of let because you want to get out of your variable(button). Also, you have to set UIButton(type: .system) because you tell that button should have some kind of style.

lazy var weiterButton: UIButton = {
    let v = UIButton(type: .system)
    v.translatesAutoresizingMaskIntoConstraints = false
    v.setTitle("WEITER", for: .normal)
    v.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 20)
    v.setTitleColor(.white, for: .normal)
    // If you want a different color when it is pressed
    v.setBackgroundImage(UIImage(named: "Hlighlighted image"), for: .highlighted)
    v.setBackgroundImage(UIImage(named: "Your image"), for: .normal)
    v.addTarget(self, action: #selector(weiterButtonTapped), for: .touchUpInside)
    return v
}()
Daveloper
  • 606
  • 5
  • 12