Swift adding the button in the program view with the action


I am trying to add button to the programatically created view that I add to main view. I can't make action to work on a button. This is what I tried so far:

itemView = UIImageView(frame:CGRect(x:0, y:0, width:240, height:375))
itemView.backgroundColor = UIColor(red: 255.0/0.0, green: 255.0/0.0, blue: 255.0/0.0, alpha: 0.05)
itemView.contentMode = .Center

buttonConnect = UIButton(frame: CGRect(x:0, y:335, width:120, height:40))
buttonConnect.backgroundColor = UIColor(red: 0.8, green: 0.6, blue: 0.2, alpha: 1.0)
buttonConnect.setTitle("Connect", forState: .Normal)
buttonConnect.tag = 3
buttonConnect.addTarget(itemView, action: "btnConnectTouched:", forControlEvents:.TouchDown)


Method on button click looks like this:

func btnConnectTouched(sender:UIButton!)
    print("button connect touched")

Can someone advice what is the problem? Thanks!

I don't understand why you are adding a button inside a UIImageView. Even this is what you need, take a UIView and then put all other controls inside it. The reason your button is not clicking is that you have put it inside a UIImageView and for UIImageView , default value for userInteractionEnabled is false. so you need to enable it i.e.

 itemView.userInteractionEnabled = true;

Also set button target to 'self' rather than itemView.