我创建了一个 UIViewController
,其中包含一个 UIView
对象。
我希望 UIView
对象响应 1 根手指的单击,以及 2 根手指的捏合。
我在 xib 中点击了“已启用用户交互”和“多点触控”选项。
我在 UIView
函数 initWithFrame: 中同时创建了 UITapGestureRecognizer
和 UIPinchGestureRecognizer
,因为它是唯一的UIView
对象的入口点。但是对象不响应 UIGestureRecognizer
对象。为什么?或者,放置 UIGestureRecognizer
对象的最佳位置在哪里?
- (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 中实例化您的自定义 View 子类时,initWithCoder:
被调用。如果您使用 initWithFrame:
以编程方式完成它,它就会正常工作。
有两种方法可以解决这个问题,
将手势设置移动到不同的方法,并在
initWithFrame:
和initWithCoder:
中调用它们。如果您打算重用此组件并公开某种手势回调,我建议您这样做。如果您只想实现一次并与 Controller 元素进行大量交互,请将它们添加到
viewDidLoad
中。
关于ios - UIView 对象中的 UIGestureRecognizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6520932/