【发布时间】: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
-
似乎自动布局是问题所在。清除自定义视图容器的约束后,它现在可以工作了。