如果在类初始化时间创建手势识别器不起作用 [英] Gesture recognizer not working if created at class init time

查看:19
本文介绍了如果在类初始化时间创建手势识别器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在集合视图中,我在类初始化时创建了一个手势识别器.在 viewDidLoad 方法中,我将手势识别器添加到集合视图中.

In a collection view, I create a gesture recognizer at class init time. In the viewDidLoad method, I then add the gesture recognizer to the collection view.

class ViewController: UIViewController {
    @IBOutlet weak var collectionView: UICollectionView!
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:)))

    @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
        // some code
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.addGestureRecognizer(longPressGesture)
    }
}

这样,手势识别器就不起作用了.

With this, the gesture recognizer does not work.

修复很简单:只需将带有 let longPressGesture 的行移动到 viewDidLoad 方法,一切都按预期工作.但是,我觉得第一个版本不起作用有点令人惊讶.

The fix is easy: it suffices to move the line with let longPressGesture to the viewDidLoad method and everything works as expected. However, I find it a bit surprising that the first version would not work.

谁能解释为什么第一个版本不起作用?是因为在创建手势识别器时,集合视图还没有准备好使用手势吗?那么,手势识别器必须了解其目标才能被创建?

Can anyone explain why the first version is not working? Is it because, when the gesture recognizer is created, the collection view is not yet ready to have gestures? So, what must a gesture recognizer know about its target in order to be created?

推荐答案

好问题.那是因为您在未完全初始化时尝试使用 self.

Good question. That's because you are trying to use self when not fully initialized.

现在,如何以您想要的方式使其工作?也许声明它懒惰,像这样:

Now, how to make that work with the way you wanted? Perhaps declare it lazily, like so:

private lazy var longPressGesture: UILongPressGestureRecognizer! = {
    let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:)))
    return gesture
}()

从这个问题中引用giorashc的回答:

Quoting giorashc's answer from this question:

由于 swift 的 2 阶段初始化,您需要初始化在继承类中使用 self 之前的父类.

Due to swift's 2-phase initialization you need to initialize the parent class before you can use self in the inheriting class.

在你的实现中,自己还没有被父级初始化类,所以你说你应该把它移到你的 init 方法查看控制器并在调用父级后创建按钮初始化方法

In your implementation self is yet to be initialized by the parent class so as you said you should move it to the init method of your view controller and create the button after calling the parent's initialization method

2 阶段初始化 SO Question &回答.

2 Phase Initialization SO Question & Answer.

这篇关于如果在类初始化时间创建手势识别器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆