如何在 ios swift 的 tableview 内添加 uilabel 的滑动手势?

2024-02-13

我正在尝试在表视图中创建检查列表。在表视图单选按钮和 UILabel 内,这里向 UILabel 添加滑动手势。对于 UILabel 的单次滑动将显示单选按钮或 UILabel 的两次滑动将显示虚线。

我尝试使用选择器方法向表内的 UILabel 添加手势,它打印成功,但 UILabel 未滑动。

这是尝试滑动 UILabel 的代码:

在viewDidLoad中:

let gestureRec = UISwipeGestureRecognizer(target: self, action: #selector(didTap(sender:)))
    tableView.addGestureRecognizer(gestureRec)
    gestureRec.delegate = self as? UIGestureRecognizerDelegate

并创建了名为 didTap 的函数:

     @objc func didTap(sender : UISwipeGestureRecognizer)
      {
      if sender.state == .ended {
        let location = sender.location(in: self.tableView)
        let indexPath = self.tableView.indexPathForRow(at: location)
        var cell = self.tableView.cellForRow(at: indexPath!) as! textCell
        print("swipe")
        cell.labelView.frame(forAlignmentRect: CGRect(x: 10, y: 8, width: 20, 
     height: 15))

    }
   }

试试这个代码。经测试,工作正常 100 %

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = tableDataSource[indexPath.row]
    cell.textLabel?.isUserInteractionEnabled = true
    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.labelSwipedLeft(sender:)))
    cell.textLabel?.addGestureRecognizer(swipeLeft)
    return cell

@objc func labelSwipedLeft(sender: UITapGestureRecognizer) {
    print("labelSwipedLeft called")
  }

See the output enter image description here


额外的:如果你想检测哪一行的标签被点击,那么为 cellForRowAt 中的标签分配一个标签,例如

cell.textLabel?.tag = indexPath.row

并在函数中获取行索引标签向左滑动 using

print("labelSwipedLeft called for row \(sender.view!.tag)")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 ios swift 的 tableview 内添加 uilabel 的滑动手势? 的相关文章

随机推荐