I'm trying to increase the hit area of a UITapGestureRecognizer on a UILabel object. This answer suggests overriding hitTest on the UILabel:
class PaddedLabel: UILabel {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
print("hitTest called")
let padding: CGFloat = 20.0
let extendedBounds = bounds.insetBy(dx: -padding, dy: -padding)
return extendedBounds.contains(point) ? self : nil
}
}
However, the problem is that hitTest is not even called unless I'm actually tapping on the object, and not somewhere close to it. Therefore, extending the bounds seems to be useless.
The label is one of a few inside a UIStackView:
let label = PaddedLabel()
let gs = UITapGestureRecognizer(target: self, action: #selector(ThisViewController.handleTap(_:)))
label.addGestureRecognizer(gs)
label.isUserInteractionEnabled = true
stackView.addArrangedSubview(label)
How do I make this work?