如果在 class 初始时间创建,手势识别器不工作
Gesture recognizer not working if created at class init time
在集合视图中,我在 class 初始时间创建了一个手势识别器。在 viewDidLoad
方法中,我将手势识别器添加到集合视图中。
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)
}
}
有了这个,手势识别器就不起作用了。
修复很简单:将带有 let longPressGesture
的行移至 viewDidLoad
方法就足够了,一切都按预期工作。但是,我觉得第一个版本不起作用有点奇怪。
谁能解释一下为什么第一个版本不起作用?是因为在创建手势识别器时,集合视图还没有准备好拥有手势吗?那么,手势识别器必须了解其目标的哪些信息才能创建?
好问题。那是因为您在未完全初始化时尝试使用 self
。
现在,如何按照您想要的方式进行操作?也许声明它 lazily,像这样:
private lazy var longPressGesture: UILongPressGestureRecognizer! = {
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:)))
return gesture
}()
编辑:引用 giorashc 的回答 :
Due to swift's 2-phase initialization you need to initialize the
parent class before you can use self in the inheriting class.
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
所以问答。
在集合视图中,我在 class 初始时间创建了一个手势识别器。在 viewDidLoad
方法中,我将手势识别器添加到集合视图中。
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)
}
}
有了这个,手势识别器就不起作用了。
修复很简单:将带有 let longPressGesture
的行移至 viewDidLoad
方法就足够了,一切都按预期工作。但是,我觉得第一个版本不起作用有点奇怪。
谁能解释一下为什么第一个版本不起作用?是因为在创建手势识别器时,集合视图还没有准备好拥有手势吗?那么,手势识别器必须了解其目标的哪些信息才能创建?
好问题。那是因为您在未完全初始化时尝试使用 self
。
现在,如何按照您想要的方式进行操作?也许声明它 lazily,像这样:
private lazy var longPressGesture: UILongPressGestureRecognizer! = {
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:)))
return gesture
}()
编辑:引用 giorashc 的回答
Due to swift's 2-phase initialization you need to initialize the parent class before you can use self in the inheriting class.
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