i have a problem with my custom UIButton. When I add a target, there is no action performed when I click. I tried to move function into ViewController class, change selector name and type, in vain. There is my code. Hope you can help me. (Hierarchy) CustomButton → MenuButtonGroup → ViewController
import UIKit
class CustomButton: UIButton {
/** vue 1 */
private let view1 = UIImageView()
/** vue 2 */
private let view2 = UIView()
/** couleur du bouton */
private var color = ""
/** décalage y pour le 3d */
private let relief = screenHeight*0.013
init(frame: CGRect, color: String){
super.init(frame: frame)
self.color = color
self.layer.cornerRadius = 10
//définir la couleur de l'ombre
switch color {
case "red":
self.backgroundColor = shadowRedColor
case "green":
self.backgroundColor = shadowGreenColor
case "blue":
self.backgroundColor = shadowBlueColor
case "yellow":
self.backgroundColor = shadowYellowColor
default:
self.backgroundColor = shadowRedColor
}
mainColorView()
self.addSubview(view2)
self.addTarget(self, action: #selector(downAction), for: .touchDown)
self.addTarget(self, action: #selector(touchUp), for: .touchUpInside)
self.addTarget(self, action: #selector(touchUp), for: .touchUpOutside)
}
/** vue de couleur principale*/
func mainColorView(){
view2.frame = CGRect(x: 0, y: -relief, width: self.frame.width, height: self.frame.height)
view2.layer.cornerRadius = 10
//définir la couleur de l'ombre
switch color {
case "red":
view2.backgroundColor = redColor
case "green":
view2.backgroundColor = greenColor
case "blue":
view2.backgroundColor = blueColor
case "yellow":
view2.backgroundColor = yellowColor
default:
view2.backgroundColor = redColor
}
}
/** appuis sur le bouton */
func downAction(sender: UIButton){
print("prout")
UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseOut, animations: {
self.view2.transform = CGAffineTransform(translationX: 0, y: self.relief)
})
}
/**relacher le bouton*/
func touchUp(){
animUp()
}
/** animer le relachement du bouton*/
func animUp(){
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.3, options: .curveEaseInOut, animations: {
self.view2.transform = CGAffineTransform.identity
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Adding the button to MenuButtonGroup :
playButton = CustomButton(frame: CGRect(x: 0, y: 0, width: 300, height: 300), color: "green")
The button is showed on screen but no action at all. I tried bringSubviewToFront but with no effect.
addTargetto it?