【问题标题】:Increasing hit area for UITapGestureRecognizer on UILabel在 UILabel 上增加 UITapGestureRecognizer 的命中区域
【发布时间】:2020-07-03 09:46:50
【问题描述】:

我正在尝试增加 UITapGestureRecognizer 在 UILabel 对象上的命中区域。 This answer 建议在 UILabel 上覆盖 hitTest:

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
    }
}

但是,问题是 hitTest 甚至没有被调用,除非我实际点击对象,而不是靠近它的某个地方。因此,扩大界限似乎没有用。

标签是 UIStackView 中的几个标签之一:

let label = PaddedLabel()
let gs = UITapGestureRecognizer(target: self, action: #selector(ThisViewController.handleTap(_:)))
label.addGestureRecognizer(gs)
label.isUserInteractionEnabled = true
stackView.addArrangedSubview(label)

我该如何进行这项工作?

【问题讨论】:

  • 解决方法可能是在其顶部添加一个透明的 uiview 并为其添加点击手势。
  • 这是个好主意。屏幕上的“点击事件”是如何传播的?什么代码决定要检查 UITapGestureRecognizer 的对象?

标签: swift cocoa-touch


【解决方案1】:

您可以像下面这样编辑PaddedLabel 来设置插图:

class PaddedLabel: UILabel {
    
    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return textRect.inset(by: invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: textInsets))
    }
}

并设置textInsets 以扩大其可点击区域。

label.textInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    相关资源
    最近更新 更多