【问题标题】:How to get data from UITableView cell to a global variable如何从 UITableView 单元格获取数据到全局变量
【发布时间】:2019-02-08 17:33:47
【问题描述】:

我正在尝试将单元格的文本保存在我的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 获取文本的任何方法,是否有可能,如果可以,如何? 提前致谢!

编辑:

发件人是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.label.text 从单元格中获取文本。
  • @RakeshaShastri 但后来我得到:“UITapGestureRecognizer”类型的值没有成员“标签”
  • 您的发件人是一个点击手势。你应该显示你的代码。这完全脱离了上下文。
  • @RakeshaShastri 我编辑了我的问题以显示代码
  • 尝试将 sender.view 转换为 UITableViewCell。然后您应该能够从单元格中访问 textLabel.text 。守卫让细胞=发件人。查看为? UITableViewCell else { return } cell.textLabel.text

标签: ios swift uitableview uiview uigesturerecognizer


【解决方案1】:

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

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

let text = cell.textLabel.text

【讨论】:

    【解决方案2】:

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

    你可以使用 来自UITableViewDelegatefunc tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)委托方法

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-01-29
      相关资源
      最近更新 更多