ios - UIView 对象中的 UIGestureRecognizer

标签 ios uiview uigesturerecognizer

我创建了一个 UIViewController,其中包含一个 UIView 对象。

我希望 UIView 对象响应 1 根手指的单击,以及 2 根手指的捏合。

我在 xib 中点击了“已启用用户交互”“多点触控”选项。

我在 UIView 函数 initWithFrame: 中同时创建了 UITapGestureRecognizerUIPinchGestureRecognizer,因为它是唯一的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: 以编程方式完成它,它就会正常工作。

有两种方法可以解决这个问题,

  1. 将手势设置移动到不同的方法,并在 initWithFrame:initWithCoder: 中调用它们。如果您打算重用此组件并公开某种手势回调,我建议您这样做。

  2. 如果您只想实现一次并与 Controller 元素进行大量交互,请将它们添加到 viewDidLoad 中。

关于ios - UIView 对象中的 UIGestureRecognizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6520932/

相关文章:

java - android中类似于iOS的VOIP推送和调用套件的调用

ios - CloudKit:备份所有服务器数据?有什么解决办法吗?

ios - iOS 中是否可以将一个控件链接到多个手势?

ios - 由于未实现的 init(frame :)),用 Swift 编写的 UIStackView 子类可能会崩溃

ios - 适用于 iOS 的滑入式菜单

ios - 为什么从 XIB 以编程方式创建 UIView 后我的 UILabel 为零? (附代码)

ios - 从 IB 加载后调整 UIView 的框架

ios - UITapGestureRecognizer - 单击和双击

ios - 将目标设置为 NSObject

ios - 如何在 Swift 中初始化 MapView