I have custom view, which contains UILabel
and I add gesture recognizer to this label in init.
protocol CustomViewDelegate: class {
func customViewDidTapOnLabel(_ customView)
}
class CustomView: UIView {
lazy var label = UILabel()
weak var delegate: CustomViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(label)
label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(labelTapped))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func labelTapped() {
delegate?.customViewDidTapOnLabel(self)
}
}
The question is, should I remove gesture recognizer in deinit? Does the label keep strong reference do UITapGestureRecognizer
?
The view owns the gesture recognizer. The superview owns the view. When your view controller's view goes out of memory, it no longer retains its supviews, which are then released (assuming nothing else is holding them). Similarly when the label is released it releases its gesture recognizers. So no you don't need to manually remove it.
But why take my word for it? You can assign your gesture recognizer to a weak global reference. Check the reference after the viewcontroller has been released and you will see that the reference is indeed nil if the only thing referencing it was a subview of the view controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With