Search code examples
iosswifttextviewuibuttonuiimageview

Image View and Label added on UIButton prevent me from tapping - Swift - Programmatically


I added a ImageView and a Label on a custom UIButton, the problem is that they prevent me from tapping the button:

class CustomSignInButton : UIButton{


override init(frame: CGRect) {
    super.init(frame: frame)
    
   
    styleButton()
    
}


required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}



fileprivate func styleButton(){
    let imageView = UIImageView(image: #imageLiteral(resourceName: "mail").withRenderingMode(.alwaysOriginal))
    imageView.contentMode = .scaleAspectFit
    
    imageView.widthAnchor.constraint(equalToConstant: 30).isActive = true
    
    let signInLabel = UILabel(text: "Sign In with Email", font: UIFont(name: "avenir-black", size: 13), textColor: .white, textAlignment: .left, numberOfLines: 1)
    
    
    let stackView = UIStackView(arrangedSubviews: [imageView, signInLabel])
    stackView.distribution = .fill
   
    
    stackView.centerYToSuperview()
    stackView.centerXToSuperview()
    stackView.spacing = 20
    self.addSubview(stackView)
    stackView.anchor(top: topAnchor, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor, padding: .init(top: 8, left: 12, bottom: 8, right: 20))
    
    
    
}
}

I actually need them set in this way but I obviously would like to know how to implement the tapping ability over those two objects.


Solution

  • Disable user interaction on imageview, label and on 'stackView'

    fileprivate func styleButton(){
            let imageView = UIImageView(image: #imageLiteral(resourceName: "mail").withRenderingMode(.alwaysOriginal))
            imageView.contentMode = .scaleAspectFit
            imageView.isUserInteractionEnabled = false
            imageView.widthAnchor.constraint(equalToConstant: 30).isActive = true
            
            let signInLabel = UILabel(text: "Sign In with Email", font: UIFont(name: "avenir-black", size: 13), textColor: .white, textAlignment: .left, numberOfLines: 1)
            signInLabel.isUserInteractionEnabled = false
            
            let stackView = UIStackView(arrangedSubviews: [imageView, signInLabel])
            stackView.distribution = .fill
           
            
            stackView.centerYToSuperview()
            stackView.centerXToSuperview()
            stackView.spacing = 20
            self.addSubview(stackView)
            stackView.anchor(top: topAnchor, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor, padding: .init(top: 8, left: 12, bottom: 8, right: 20))
            
            
            
        }