IOS swift 如何在点击标签时获取 TableView 中的标签文本

IOS swift how can I get label text inside a TableView on label tap

我有一个 TableView,其中通过标签在其中包含数据。当您单击标签时,Tap 会注册,但现在 我想获取所单击标签的数据,但我很难完成这项工作。我对 Buttons 有相同的功能,例如,这就是我在 TableView 中为我的按钮做的。

按钮点击事件

      var locations = [String]()
      @IBOutlet weak var Location: UIButton!
     override func viewDidLoad() {
        super.viewDidLoad()
        TableSource.dataSource = self


    }
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Registration_Search", for: indexPath)

        cell.Location.setTitle(locations[indexPath.row], for: UIControlState.normal)

        cell.Location.addTarget(self, action: #selector(Registration_SearchController.Location_Click(sender:)), for: .touchUpInside)
        cell.Location.tag = indexPath.row

        return cell
    }

   func Location_Click(sender: UIButton) {

         print(locations[sender.tag])


    }

上面的代码允许我获取任何被点击的按钮的数据。我现在尝试对 Label 执行相同的操作,但无法获取 Label 拥有的数据。这是我的标签代码,哦,与上面相同,但不同 ViewController

      var locations = [String]()
      @IBOutlet weak var location: UILabel!
     override func viewDidLoad() {
        super.viewDidLoad()
        TableSource.dataSource = self
        location.isUserInteractionEnabled = true

    }
            func tapFunctionn(sender: UITapGestureRecognizer)
{
   // I would like to get the data for the tapped label here
    print("Tapped")
}
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Registration_Search", for: indexPath)

          cell.location.text = Locations[indexPath.row]
          let tap = UITapGestureRecognizer(target:self, action: #selector(HomePageC.tapFunctionn))

    cell.location.addGestureRecognizer(tap)

        return cell
    }

再次单击标签时,它会打印 Tapped 但无法获取实际数据。在 Button 函数中我可以使用 Sender.Tag 但 UITapGestureRecognizer 没有 Tag 方法。任何建议将不胜感激

您不必使用 UITapGestureRecognizer。只需使用委托方法。将 UITableView 委托设置为您的 UIViewController 并使 class 符合 UITableViewDelegate

为swift3

override func viewDidLoad() {
    super.viewDidLoad()
    TableSource.dataSource = self
    TableSource.delegate = self
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)

    //access the label inside the cell
    print(cell.label?.text)
    //or you can access the array object
    //print(Locations[indexPath.row])
}

你可以做这样的事情:

func tapFunctionn(recognizer: UIPinchGestureRecognizer) {
  let view = recognizer.view
  let index = view?.tag
  print(index)
}