Swift, custom UIButton does not work if clicked

I have a custom UIButton created using an xib file. When I use my custom button on my view, it does not work when I click on it.

My RoundBtn.swift file:

import UIKit @IBDesignable class RoundBtn: UIButton { var nibName = "RoundBtn" @IBOutlet weak var btnImageView: UIImageView! @IBOutlet weak var btnLabel: UILabel! @IBInspectable var image: UIImage? { get { return btnImageView.image } set(image) { btnImageView.image = image } } @IBInspectable var label: String? { get { return btnLabel.text } set(label) { btnLabel.text = label } } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { let view = loadViewFromNib() view.frame = self.bounds view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] btnImageView.layer.cornerRadius = 60/2 btnImageView.layer.borderColor = UIColor(red: 5/255, green: 66/255, blue: 38/255, alpha: 1).CGColor btnImageView.layer.borderWidth = 2 btnLabel.font = UIFont.boldSystemFontOfSize(14.0) btnImageView.userInteractionEnabled = true btnLabel.userInteractionEnabled = true view.userInteractionEnabled = true addSubview(view) } func loadViewFromNib() -> UIButton { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: nibName, bundle: bundle) let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIButton return view } } 

My RoundBtn.xib file:

enter image description here

See where I used my custom button:

enter image description here

I have included userInteractionEnabled for all view components. When I click on my custom button, it does not work. I tried to detect a software click and to determine the action of segue (show).

 @IBAction func myCartBtnPressed(sender: AnyObject) { print("my cart btn pressed") } 
+5
source share
2 answers

I think this is because you are adding a few UIViews pods to your current UIButton with userInteractionEnabled, which means that they handle user input.

If you do:

 view.isUserInteractionEnabled = false 

RoundBtn itself will receive all the touch events, not the UIViews that you have.

+12
source

Referring to @fdiaz answer. Swift 4.

Conversely, if you attach some UIButton (or user interactive view) to the UIImageView, you must turn it isUserInteractionEnabled = true so that the strokes pass through the hierarchy up to UIButton.

0
source

Source: https://habr.com/ru/post/1242707/


All Articles