gpt4 book ai didi

ios - 使用 UITapGestureRecognizer 从点击的单元格中获取标签文本

转载 作者:行者123 更新时间:2023-11-28 07:23:26 24 4
gpt4 key购买 nike

我想在点击单元格标签时编辑标签文本(不是 didSelectRowAt)。 Tapped 标签函数 (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)
}

错误如下:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

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

最佳答案

问题出在您的 customTableViewController 变量上。它指的是表格 View 中从未出现过的无用单元格。摆脱它。没必要。

从点击手势获取单元格。点击手势有一个 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))

除非您出于某种原因实际实现了手势委托(delegate)方法,否则请删除该行:

tapGesture.delegate = self as? UIGestureRecognizerDelegate

同时删除多余的行:

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

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

关于ios - 使用 UITapGestureRecognizer 从点击的单元格中获取标签文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57317229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com