以按钮目标通过程序创建的自定义视图

问题描述 投票:1回答:3

我有一个自定义的UIView子类,该子类附加了一些UIButtons。对于每个按钮,在UIViewController上定义了目标动作,其中包括自定义UIView

以某种方式<< TouchUpInside事件不会被捕获在包括ViewController在内的自定义视图中。由于UIViews是UIResponderChain的一部分,所以我想知道为什么不触发事件吗?委派目标动作是否有意义,还是应该以其他方式完成?

Custom UIView子类:CustomView

let button = UIButton(frame: CGRectMake(10.0, 10.0, 100.0, 100.0)) button.addTarget(self.delegate, action: "buttonTapped:", forControlEvents: .TouchUpInside)

ViewController

// Include the custom view let customView = CustomView() customView.delegate = self self.view.addSubview(customView) ... func buttonTapped(sender: AnyObject!) { // Doesn't get called }
ios objective-c cocoa-touch swift uiview
3个回答
1
投票
您是否在自定义视图上将userInteractionEnabled设置为YES?在不是从NO降级的视图上(默认是按钮),默认情况下为UIResponder

如果视图为userInteractionEnabled = NO,它将忽略触摸事件。


0
投票
我假设添加目标时self.delegate为零...很少的解决方案:

    使用委托初始化自定义视图(创建自定义函数initWithFrame:delegate)
  • 覆盖自定义视图的setDelegate函数,并在其中向按钮添加目标;
  • 公开按钮变量,并在您的外部类中手动添加目标

0
投票
不幸的是,我缺少为按钮声明框架的正确性-因此按钮一直在显示,但是它们确实不可单击。
© www.soinside.com 2019 - 2024. All rights reserved.