我可能有所遗漏,但是...
我有一个带有几个子项的 UIView
(一些UILabel
和UIImageView
)。我需要在用户单击(轻敲)父 UIView
(可见部分或其任何子项)时捕获事件。
最好的方法是什么?
我可能有所遗漏,但是...
我有一个带有几个子项的 UIView
(一些UILabel
和UIImageView
)。我需要在用户单击(轻敲)父 UIView
(可见部分或其任何子项)时捕获事件。
最好的方法是什么?
UIControl
,然后您就可以为视图添加一个UITouchUpInside
事件-以捕获对其的轻敲。UIView
添加一个手势识别器以监听轻敲事件。如果parentView
是包含子视图(UILabels
/UIImageView
)的视图,并且handleTap
是由parentView
实现的方法,则可以执行以下操作:UIGestureRecognizer *tapParent = [[UITapGestureRecognizer alloc]initWithTarget:parentView action:@selector(handleTap)];
[parentView addGestureRecognizer:tapParent];
[tapParent release];
这对我有效
Swift 3
(注:此处为编程语言名称) let gesture = UITapGestureRecognizer(target: self, action: selector(self.customViewClick))
withSender: self)
customView.addGestureRecognizer(gesture)
func customViewClick() {
print("custom view clicked!")
}
你需要提供更多细节,因为有多个选项可供选择。
如果你想要普通的点击事件,你可以捕获其中一个标准的触摸事件,并查看哪个子视图接收到了该事件。类似于这样:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if(touch.view != self.mySubViewOfInterest)
{
// perform my actions
}
}
Swift 4:
let clickGesture = UITapGestureRecognizer(target: self, action: #selector(self.onUiViewClick))
uiView.addGestureRecognizer(clickGesture)
@objc func onUiViewClick(sender : UITapGestureRecognizer) {
}