【问题标题】:How do I use indexpathforselectedrow to get an instance from my array of structs?如何使用 indexpathforselectedrow 从我的结构数组中获取实例?
【发布时间】:2019-07-24 09:08:26
【问题描述】:

我正在为学校构建一个应用程序。该应用程序类似于字典应用程序,其中包括嵌入到导航控制器中的词汇表(我的 WordsTableViewController),以及显示词汇及其相应定义的定义视图控制器。

问题是我不知道如何使用 indexpathforselectedrow 从我的 vocabController 的 vocabWords 数组中获取适当的词汇。 “词汇”是位于其自己单独的 swift 文件中的结构实例。

所有这些都将在我的 WordsTableViewController swift 文件中为 segue 做准备。

非常感谢任何帮助。

表格视图的行数如下所示:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myListVocab.vocabWords.count
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowDefinitionSegue" {
        if let definitionVC = segue.destination as? DefinitionViewController {
            let index = tableView.indexPathForSelectedRow
            let indexPathForSelectedRow = index.row
            definitionVC.vocabWord[index]
            let vocab = myListVocab.vocabWords[indexPathForSelectedRow]
        }
    }
}

我得到的错误是我对成员 tableView(_:numberOfRowsInSection:) 的引用不明确

到目前为止,我的程序中的其余错误是“只能在类成员上指定覆盖”

【问题讨论】:

    标签: swift xcode uitableview segue


    【解决方案1】:

    首先在您的WordsTableViewController 中实现didSelectRow。然后创建实例变量selectedWord。之后就可以通过调用得到didSelectRow中选中的单词:

    selectedWord = myListVocab.vocabWords[indexPath.row]

    赋值后,可以在prepareForSegue中使用selectedWord

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         if segue.identifier == "ShowDefinitionSegue" {
              if let definitionVC = segue.destination as? DefinitionViewController {
                     destinationVC.word = selectedWord
              }
          }
    }
    

    【讨论】:

    • 谢谢。在尝试了这段代码之后,我的故事板上的视图控制器变黑了,我的模拟器也消失了。我收到错误“无法使用仅构建设备来运行此目标”如何将其更改回来?我不确定我是否理解发生了什么,因为你的回答对我来说很有意义。
    • 故事板问题与我发布的代码无关。 XCode 似乎坏了,请尝试重新启动它。
    • 我的应用仍然无法构建。好的,我收到了这些错误。 imgur.com/ltC0Zc1 imgur.com/39SHuWd .. 希望在我的截图中可以看得很清楚。
    【解决方案2】:

    而不是在prepare(for:sender:) 中手动推送DefinitionViewController UITableViewDelegate's tableView(_: didSelectRowAt:) 方法,即

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let definitionVC = self.storyboard?.instantiateViewController(withIdentifier: "DefinitionViewController") as? DefinitionViewController {
            let word = myListVocab.vocabWords[indexPath.row] //get the word using indexPath...
            definitionVC.word = word //set the word in definitionVC's property...
            self.navigationController?.pushViewController(definitionVC, animated: true)
        }
    }
    

    不要忘记在storyboard 中将DefinitionViewControllerStoryboard ID 设置为DefinitionVC

    另外,删除您在storyboard 中创建的segue。否则,DefinitionViewController 将被不必要地推送两次。

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 2011-12-29
      • 2021-04-03
      • 2011-10-08
      • 2014-03-07
      • 2022-10-06
      相关资源
      最近更新 更多