Swift - UIButton以编程方式创建并不会触发触摸事件

时间:2017-01-07 12:59:07

标签: ios swift events uibutton

我已经以编程方式创建了一个按钮,并希望添加一个触摸事件处理程序。我已经尝试了我在网上找到的所有技巧,但是从未触发过所需的功能。

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)

并定义了这个

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

但这永远不会被召唤。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您需要在upgradeTapped实例的类中定义side_menu_controller函数。我猜,它是SideMenuController类。

答案 1 :(得分:0)

我发现这是因为我将按钮放在视图旁边但在界限之外(仅在顶部):

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

有两种解决方法:

  • 在父视图的边界内移动按钮,或
  • 通过覆盖“hitTest”来处理视图之外的内容,如here所述