繁体   English   中英

如何在表格视图中获取选定行的文本? (迅速)

[英]How do I get the text of a selected row in a table view? (Swift)

如何获取 UITableView 中选定单元格的文本? 例如,我知道如何获取行( indexPath.row ),但我找不到如何获取所选单元格的内容。


大图:

最终,我想使用单元格来 select 适当的 segue。 我正在为 UITableView 的单元格的文本使用 plist。 当用户选择表中的一个项目时,选择了segue。

我是这样设置的:

switch indexPath.row {
    case 0: segueIdentifier = "segueToTopic0"
    case 1: segueIdentifier = "segueToTopic1"
    // etc.
    default: segueIdentifier = "segueTest"
}

但最终经常添加和删除项目,或者重新排列 plist,迫使我重新排列这个 switch 语句。

所以,现在我想我可以通过使用 switch 语句中的单元格文本来做到这一点:

switch indexPath.row {
    case "Topic0": segueIdentifier = "segueToTopic0"
    case "Topic1": segueIdentifier = "segueToTopic1"
    // etc.
    default: segueIdentifier = "segueTest"
}

(当然,这意味着我必须确保 plist 中的文本和 switch 语句中的文本相同。)

或者也许有更好的方法?

在这里提出问题时,最好考虑一下您要问的内容以及您要问的原因

如果没有额外的上下文,您的方法似乎没有多大意义。

“我正在为 UITableView 的单元格的文本使用 plist” ......你的 plist 中可能有 100 个“主题”吗? 这意味着您手动创建并命名了 100 个 segue 连接? 可能有更好的方法。

但是,要回答您的具体问题...

我们假设您已将 plist 中的数据加载到一个字符串数组中,可能称为arrayOfTopics ...加载后,它将是这样的:

arrayOfTopics [
    "Topic0",
    "Topic1",
    "Topic2",
    "Topic3",
    "Topic4",
    "Topic5",
]

因此,您的cellForRowAt实现看起来像这样:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = arrayOfTopics[indexPath.row]
    return cell
}

与其思考“如何从一行中获取文本”,不如使用相同的数据结构,所以didSelectRowAt可能如下所示:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let segueID: String = "segueTo" + arrayOfTopics[indexPath.row]
    performSegue(withIdentifier: segueID, sender: nil)
}

如果您点击第 3 行(行和 arrays 是从零开始的), indexPath.row将为 2... arrayOfTopics[2] 包含“Topic2”... 将其附加到“segueTo”将产生字符串segueToTopic2 ,然后,您可以将其用作 segue 标识符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM