【问题标题】:UIButton action not called inside custom view自定义视图中未调用 UIButton 操作
【发布时间】:2015-08-26 17:02:01
【问题描述】:

我想制作一个自定义视图,其中包含以下内容:

  • 绿色景观
  • 在绿色视图中的图像视图
  • 在这另一个白色视图之上
  • 白色视图之上的另一个图像视图
  • 还有一个 UIButton

这是我在自定义视图中的代码:

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 设置为 true
  • 似乎自动布局是问题所在。清除自定义视图容器的约束后,它现在可以工作了。

标签: ios swift


【解决方案1】:

您发布的代码运行良好,问题在于包含您所有视图的容器视图,可能userInteractionEnabled 对于容器视图是错误的。

【讨论】:

  • 自定义视图容器还将 userInteractionEnabled 设置为 true
  • 好的,现在好像可以了。我清除了自定义视图容器的约束,现在它可以工作了。所以自动布局是个问题。
【解决方案2】:

按钮用户交互默认开启,无需显式设置。

【讨论】:

  • 不需要在类中声明,视图也有引用(添加为子视图后)所以它不会被释放
  • addSubview 将添加视图并持有对它们的强引用并且不会被释放
  • 那么简单地按钮交互被阻止任何其他视图。
猜你喜欢
  • 2013-04-10
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多