UIView 对象中的 UIGestureRecognizer [英] UIGestureRecognizer in UIView Object
问题描述
我创建了一个 UIViewController
,其中包含一个 UIView
对象.
I have created a UIViewController
, which contains a UIView
object.
我希望 UIView
对象响应 1 根手指单击和 2 根手指捏合.
I want the UIView
object response to a single tap by 1 finger, and also pinch by 2 fingers.
我点击了 xib 中的启用用户交互"和多点触控"选项.
I have clicked the "User Interaction Enabled" and the "Multiple touch" options in the xib.
我在 UIView
函数 initWithFrame: 中创建了 UITapGestureRecognizer
和 UIPinchGestureRecognizer
,因为它是唯一的UIView
对象的入口点.但是该对象不响应 UIGestureRecognizer
对象.为什么?或者,放置 UIGestureRecognizer
对象的最佳位置在哪里?
I create both UITapGestureRecognizer
, and UIPinchGestureRecognizer
inside the UIView
function initWithFrame:, as it is the only entry point for the UIView
object. But the object doesn't response to the UIGestureRecognizer
objects. Why? Or, where is the best place to put the UIGestureRecognizer
objects?
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
// single tap
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[self addGestureRecognizer: singleTap];
// 2 fingers pinch
UIPinchGestureRecognizer* doubleMove = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleMove:)];
[self addGestureRecognizer: doubleMove];
}
return self;
}
推荐答案
您的问题是,当您在 IB 中实例化自定义视图子类时,会调用 initWithCoder:
.如果您使用 initWithFrame:
以编程方式完成它,它会正常工作.
Your problem is that when you instantiate your custom view subclass in IB, initWithCoder:
is called. If you had done it programmatically using initWithFrame:
it would have worked properly.
有两种方法可以解决这个问题,
Two ways you can fix this,
将手势设置移动到不同的方法,并在
initWithFrame:
和initWithCoder:
中调用它们.如果您打算重用此组件并公开某种手势回调,我建议您这样做.
Move the gestures setup to a different method and call them in both
initWithFrame:
andinitWithCoder:
. I would recommend doing this if you intend to reuse this component and expose some kind of callbacks on gestures.
如果您想实现一次并与控制器元素进行大量交互,请将它们添加到 viewDidLoad
中.
If you want to implement this once and have a lot of interacting with the controller element, add them in viewDidLoad
.
这篇关于UIView 对象中的 UIGestureRecognizer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!