【问题标题】:Increase tap area for UITapGestureRecognizer on UILabel when size of the label increases当标签大小增加时,增加 UILabel 上 UITapGestureRecognizer 的点击区域
【发布时间】:2021-03-24 11:40:50
【问题描述】:

我在 UICollectionViewCell 上有一个 UILabel。在 UILabel 上,我附加了一个 UITapGestureRecognizer。当 UILabel 的宽度增加时,我正在尝试增加 UILabel 上的 UITapGestureRecognizer 的点击区域。

这里是代码示例:

class BusCell: UICollectionViewCell {

    var bus: Bus!
    var tapGesture: UITapGestureRecognizer!
    
    @IBOutlet weak var nameLabel: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        addTapGestureToNameLabel()
    }
    
    // MARK: - UI
    
    func addTapGestureToNameLabel() {
        tapGesture = UITapGestureRecognizer(target: self, action: #selector(nameLabelDoubleTap(gesture:)))
        tapGesture.numberOfTapsRequired = 2
        nameLabel.addGestureRecognizer(tapGesture)
        nameLabel.isUserInteractionEnabled = true
    }
    
    func configure(_ bus: Bus, isStereo: Bool = false) {
        self.bus = bus

        loadCellUI(bus: bus)

        bus.updateBlock = { [weak self] in
            
            guard let strongSelf = self else {
                return
            }
            
            strongSelf.loadCellUI(bus: bus)
        }
    }
    
    func loadCellUI(bus: Bus) {
        nameLabel.frame = CGRect(x: CGFloat(0), y: yPosition, width: 122, height: self.nameLabel.frame.height)
                
        if bus.isStereo {
            if bus.index % 2 == 0 {
                let frame = nameLabel.frame
                nameLabel.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: 244, height: frame.height)
                nameLabel.isHidden = false
                // Make the tap frame same as the nameLabel's frame
            } else {
                nameLabel.isHidden = true
            }
        } else {
            let frame = nameLabel.frame
            nameLabel.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: 122, height: frame.height)
            nameLabel.isHidden = false
            // Make the tap frame same as the nameLabel's frame
        }
    }
}

我该如何进行这项工作?

【问题讨论】:

    标签: ios swift uitapgesturerecognizer


    【解决方案1】:

    点击手势识别器附加到视图,并响应视图框架内的点击。它没有自己的水龙头区域。如果您增加标签的大小,那么点击区域的大小也应该增加。

    我记得读过 Apple 的建议,可点击区域至少为 40x40 点。您可能希望在略大于标签的标签顶部放置一个不可见视图(称为 tapView)(您可以获取标签的框架,并调用 CGRect.inset(by:) 并为所有边缘设置负值。使用生成的矩形作为tapView 的框架,并在标签顶部添加点击视图。)如果你这样做,那么你应该把代码放在你的视图控制器的viewDidLayoutSubviews() 方法中(并且任何时候你改变你的nameLabel label) 来调整tapView的框架。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      相关资源
      最近更新 更多