如何在iOS Swift中的TableView中为UILabel添加滑动手势? [英] How to add swipe gesture for uilabel inside tableview in ios swift?

查看:62
本文介绍了如何在iOS Swift中的TableView中为UILabel添加滑动手势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在表格视图中创建检查列表.内部表格视图单选按钮和UILabel,此处向UILabel添加了滑动手势.对于UILabel的单次滑动将显示单选按钮,对于UILabel的两次滑动将显示虚线.

I am trying to creating check list in a table view. Inside table view radio button and UILabel, here adding swipe gesture to UILabel. For single swipe of UILabel will show radio button or double swipe of UILabel will show dash line.

我尝试通过使用选择器方法在表内的UILabel中添加手势,它可以成功打印,但是UILabel没有滑动.

I have tried of adding gesture to UILabel inside table by using selector method, it print successfully but UILabel is not swiping.

以下是刷过UILabel的代码:

Here is the code tried of swiping UILabel:

在viewDidLoad中:

In viewDidLoad:

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

并创建了名为didTap的函数:

And created function called 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")
  }

查看输出

其他:如果要检测点击了哪个行的标签,则可以像在cellForRowAt中一样为该标签分配一个标签

Additional: If you want to detect which row's label was tapped, then assign a tag to the label in cellForRowAt like

cell.textLabel?.tag = indexPath.row

并使用

print("labelSwipedLeft called for row \(sender.view!.tag)")

这篇关于如何在iOS Swift中的TableView中为UILabel添加滑动手势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆