Background: I am creating a button with an image and a label. I add the label to the button with button.addSubview(labelName)
and then I add the button to the main view with self.view.addsubview(buttonName)
. I am creating all views programatically and with UIKit. I do not use SwiftUI or Storyboard.
Problem: When pressing the button and holding the press, by default the button image automatically gets darker and loses color (I do not know what this animation or action is called, but I guess it's some kind of default button press/click action). The gif below shows this animation. The problem is, only the background image of the button is affected. The label and the label background, that I added to the button, are not effected by this dim animation.
What I want to achieve: I want the label and the label background to get the same dim effect, when the button is pressed. I don't like the way the label stands out with its bright colors while the button is pressed. Do I need to recognize the click and add some kind of dim animation to all childviews of the button manually or should I avoid adding labels to buttons like I did in the code below?
Simplified code for testing:
func doStuff(){
let testbutton = UIButton(frame: CGRect(x: self.view.frame.width/4, y: 100, width: 200, height: 130))
let testImg = UIImage(named: "rand.jpeg")
testbutton.setImage(testImg, for: .normal)
testbutton.addTarget(self, action: #selector(otherStuff), for: .touchUpInside)
let label = UILabel(frame: CGRect(x: testbutton.bounds.origin.x+20, y: testbutton.bounds.origin.y+20, width: 150, height: 50))
label.text = "NOT EFFECTED"
label.backgroundColor = .red
testbutton.addSubview(label)
self.view.addSubview(testbutton)
}