如何使用自动布局在子视图中创建 UIGestureRecognizer?

How to create UIGestureRecognizer in subview with Autolayout?

当我尝试在子视图中使用 UIGestureRecognizer 时,其框架是通过 superviewcontroller 中的自动布局指定的,它不响应手势。我相信这是因为手势识别器不知道视图的真实尺寸,正如自动布局约束所描述的那样。这怎么能解决?这是我的代码:

import UIKit
class MyLabel: UILabel {
    var delegate: MyProtocolForSwipeRecognition!
    var gestureRecognizer: UISwipeGestureRecognizer
    init() {
        gestureRecognizer = UISwipeGestureRecognizer(target: delegate, action: "swiped")
        super.init(frame: CGRect()) //<- I believe my problem is because it thinks
        //the frame is this empty CGRect, but I don't know what else to put here.
        translatesAutoresizingMaskIntoConstraints = false
        addGestureRecognizer(gestureRecognizer)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

提前致谢。

您的方法有两个问题(自动布局不是问题):

  1. 您必须在 MyLabel class
  2. 上设置 userInteractionEnabled = true
  3. 添加手势识别器时,必须确保delegate不为零。您可以通过添加一个将委托作为参数
  4. 的初始化程序来做到这一点

这是让它工作的方法(无需保留对手势识别器的引用):

class MyLabel: UILabel {
    var delegate: MyProtocolForSwipeRecognition

    init(withDelegate delegate: MyProtocolForSwipeRecognition) {
        self.delegate = delegate
        let gestureRecognizer = UISwipeGestureRecognizer(target: delegate, action: "swiped")
        super.init(frame: CGRectZero)
        addGestureRecognizer(gestureRecognizer)
        userInteractionEnabled = true
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

然后你可以在实现你的协议的class中初始化你的标签:

let label = MyLabel(withDelegate: self)