如何从 UITableView 单元格获取数据到全局变量

How to get data from UITableView cell to a global variable

我正在尝试将单元格的文本保存在 UITableView 中供以后使用。我在不同的 Stack Overflow 帖子上看到建议使用

sender.view

当我将它打印到控制台时,响应是:

Optional(<UITableViewCell: 0x7f8e0a803400; frame = (0 0; 375 50); text = 'Event 1'; clipsToBounds = YES; autoresize = W; gestureRecognizers = <NSArray: 0x60400024f150>; layer = <CALayer: 0x60400002b940>>)

但是当我尝试访问时

sender.view?.text

XCode 显示错误

Value of type 'UIView' has no member 'text'

我还没有找到任何从 UIView 获取文本的方法,这是否可能,如果可以的话怎么办? 提前致谢!

编辑:

sender 是 UITapGestureRecognizer 我正在从按下按钮传递到方法中

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->   UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
    tapGesture.numberOfTapsRequired = 1
    tapGesture.numberOfTouchesRequired = 1
    cell.textLabel?.text = mydata[indexPath.item]
    cell.addGestureRecognizer(tapGesture)
    cell.isUserInteractionEnabled = true
    return cell
}


@objc func handleTapGesture(sender: UITapGestureRecognizer) {
    performSegue(withIdentifier: "SegueToScanner", sender: self)
}

尝试将 sender.view 转换为 UITableViewCell,然后您应该能够访问单元格的 textLabel。

guard let cell = sender.view as? UITableViewCell else {
    //error handling
    return
}

let text = cell.textLabel.text

不确定为什么要在 tableView 单元格上使用点击手势识别器。这是另一个可能对您有用的解决方案。

你可以使用 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 来自 UITableViewDelegate

的委托方法

在你的情况下,它应该看起来像这样。

extension YourViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? UITableViewCell {
             let text = cell.textLabel?.text
    }
}

确保您的 ViewController 符合 viewDidLoad

中的 UITableViewDelegate