【问题标题】:Get label text from tapped cell with UITapGestureRecognizer使用 UITapGestureRecognizer 从点击的单元格中获取标签文本
【发布时间】:2019-08-01 21:31:03
【问题描述】:

我想在点击单元格标签时编辑标签文本(不是didSelectRowAt)。 Taped 标签函数 (toDoItemLabelTapped) 显示 nil。

虽然UITapGestureRecognizer 运行良好,但它不会传递标签文本。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as!  ToDoItemsCell

    cell.delegate = self

    cell.textField.delegate = self
    cell.textField.isHidden = true
    cell.toDoItemLabel.isUserInteractionEnabled = true

    let aSelector : Selector = Selector(("toDoItemLabelTapped"))
    var tapGesture = UITapGestureRecognizer(target: self, action: aSelector)

    tapGesture.numberOfTapsRequired = 1
    cell.addGestureRecognizer(tapGesture)
    tapGesture.delegate = self as? UIGestureRecognizerDelegate
    tapGesture = UITapGestureRecognizer(target: self, action: aSelector)

    return cell
}

这里是函数:

var customTableViewController = ToDoItemsCell()

@objc func toDoItemLabelTapped() {
    print(customTableViewController.toDoItemLabel.text)
}

错误如下:

致命错误:在隐式展开可选值时意外发现 nil

如何让点击手势通过单元格的标签文本?

【问题讨论】:

  • 使用闭包。

标签: ios swift uitableview uitapgesturerecognizer


【解决方案1】:

问题在于您的 customTableViewController 变量。它指的是一个从未出现在表格视图中的无用单元格。摆脱它。没必要。

通过点击手势获取单元格。点击手势具有view 属性。由于您将点击手势添加到单元格,其view 属性将是单元格。

@objc func toDoItemLabelTapped(_ gesture: UITapGestureRecognizer) {
    let cell = gesture.view as! ToDoItemsCell
    print(cell.toDoItemLabel.text)
}

您还需要修复cellForRowAt 中的选择器。去掉 aSelector 变量。

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toDoItemLabelTapped))

除非您出于某种原因实际实现了手势委托方法,否则请去掉这行:

tapGesture.delegate = self as? UIGestureRecognizerDelegate

同时删除多余的行:

tapGesture = UITapGestureRecognizer(target: self, action: aSelector)

另请注意,单元格被重复使用,因此当用户滚动时,您会向每个单元格添加越来越多的点击手势。您可能希望避免向任何单元格添加多个点击手势。

【讨论】:

  • “你可能想避免……”应该读作“你绝对应该避免……”一遍又一遍地添加一个具有相同目标和动作的 gr。查看developer.apple.com/documentation/uikit/uiview/… 以了解如何测试该条件。
  • @danh 感谢您的评论!在我的情况下,我需要应用 removeGestureRecognizer,但我怎样才能阻止单元格重复使用?
  • @rmaddy,感谢您的解决方案,它成功了!现在我需要使用func textFieldShouldReturn(_ userText: UITextField) -> Bool 来停止编辑文本字段。如何在那里定义单元格?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
相关资源
最近更新 更多