简体   繁体   中英

Swift - UIButton created programatically doesn't trigger touch event

I have created a button programatically and want to add a touch event handler. I have tried all the tricks I have found online but the desired function is just never triggered.

upgradeNowView = UIButton()
upgradeNowView.setTitle("Upgrade", forState: .Normal)
upgradeNowView.contentMode = UIViewContentMode.ScaleToFill
upgradeNowView.frame = CGRect(x: upgradeNowView.frame.minX, y: -50 , width: 320, height: 50)
upgradeNowView.userInteractionEnabled = true
upgradeNowView.sendActionsForControlEvents(.TouchUpInside)
upgradeNowView.addTarget(self, action: #selector(MainViewContainer.upgradeTapped(_:)), forControlEvents: .TouchUpInside)
side_menu_controller?.view.addSubview(upgradeNowView)

and defined this

func upgradeTapped(sender: UIButton)
{
    UpgradeViewController.openUpgrade()
}

But this just never gets called. Any help would be appreciated.

You need to define upgradeTapped function in class of side_menu_controller instance. I guess, it's SideMenuController class.

I found out this was caused by the fact that I was placing the button next to the view but outside its bounds (just on top):

upgradeNowView.frame = CGRect(x: upgradeNowView.frame.minX, y: -50 , width: 320, height: 50)

There are two ways around this:

  • Move the button inside the bounds of the parent view, or
  • Handle touches outside the view by overriding "hitTest" as discussed here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM