繁体   English   中英

在自定义视图中未调用UIButton操作

[英]UIButton action not called inside custom view

我要创建一个自定义视图,其中将包含以下内容:

  • 绿景
  • 在绿色视图内的图像视图
  • 在另一个白色视图之上
  • 在白色视图之上的另一个图像视图
  • 最重要的是

这是我的代码,它位于自定义视图中:

func setup() {

    // add green view
    let greenView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
    greenView.backgroundColor = UIColor.greenColor()
    greenView.userInteractionEnabled = true
    addSubview(greenView)

    // add first image
    let image1 = UIImageView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
    image1.image = UIImage(named: "checked2")
    image1.userInteractionEnabled = true
    greenView.addSubview(image1)

    // add white image
    let whiteView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
    whiteView.backgroundColor = UIColor.yellowColor()
    whiteView.userInteractionEnabled = true
    greenView.addSubview(whiteView)

    // add second image
    let image2 = UIImageView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
    image2.image = UIImage(named: "checked")
    image2.userInteractionEnabled = true
    whiteView.addSubview(image2)

    // add button
    let button = UIButton(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
    button.backgroundColor = UIColor.redColor()
    button.addTarget(self, action: Selector("animation:"), forControlEvents: UIControlEvents.TouchUpInside)
    button.userInteractionEnabled = true
    addSubview(button)



}

func animation(button: UIButton) {
    print("tapped")
}

红色按钮出现在顶部,但单击该按钮时不会调用该操作。
我试图在所有元素上设置userInteractionEnabled ,但是没有任何效果。

您发布的代码运行正常,问题出在包含所有视图的容器视图中,也许userInteractionEnabled对于容器视图为false。

默认情况下,按钮用户交互是打开的,无需显式设置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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