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



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

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获取文本的方法,甚至可能吗,如果有的话,如何? 提前感谢!

编辑:

发件人是我通过按下按钮传递到方法中的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符合UITableViewDelegateviewDidLoad

最新更新