Ios 在Swift中不使用Segue向前传递数据
我目前正在使用Swift 4制作一个待办事项列表应用程序。主视图控制器有一个包含某些类别的tableview,当选择一个类别时,它会将用户带到视图控制器,其中列出了该类别中的项目。但是我有一个bug,因为列表中只显示了最近的项目 我认为这是由于我导航到列表视图控制器的方式。我目前正在这样做:Ios 在Swift中不使用Segue向前传递数据,ios,swift,core-data,segue,Ios,Swift,Core Data,Segue,我目前正在使用Swift 4制作一个待办事项列表应用程序。主视图控制器有一个包含某些类别的tableview,当选择一个类别时,它会将用户带到视图控制器,其中列出了该类别中的项目。但是我有一个bug,因为列表中只显示了最近的项目 我认为这是由于我导航到列表视图控制器的方式。我目前正在这样做: func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let destinationVC =
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let destinationVC = ListVC()
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedCategory = categoryArray[indexPath.row]
}
navigationController?.pushViewController(destinationVC, animated: true)
tableView.deselectRow(at: indexPath, animated: true)
}
在列表视图控制器中,我只需加载以下数据:
var selectedCategory : Category? {
didSet {
loadItems()
}
}
我首先使用故事板创建了这个应用程序,当使用segues时,它运行得非常好
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToItems", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! TodoListVC
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedCategory = categoryArray[indexPath.row]
}
}
因此,基本上,问题是在次要列表视图控制器中,它只显示最近添加的项,而不显示其他项,即使它们存储在核心数据中。我认为这与我每次创建新对象时显示次视图控制器的方式有关
如果有人对如何正确转到下一个视图控制器有任何建议,将不胜感激
谢谢我想通过这段代码,我已经感觉到您正在以错误的方式将数据传递给另一个视图控制器:
let destinationVC = ListVC()
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedCategory = categoryArray[indexPath.row]
}
我的建议是,不要以这种方式传递数据,而是使用数组传递包含所选类别中的项目的数组,然后通过prepare for segue传递该数组
然后从接收视图控制器中的ViewDidDisplay或viewdidload方法,使用从源VC传递的数组,并将其用作该第二个VC中的表视图的数据源
我希望这是有道理的。:-) 我认为,通过这段代码,我已经感觉到您正在以错误的方式将数据传递给另一个视图控制器:
let destinationVC = ListVC()
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedCategory = categoryArray[indexPath.row]
}
我的建议是,不要以这种方式传递数据,而是使用数组传递包含所选类别中的项目的数组,然后通过prepare for segue传递该数组
然后从接收视图控制器中的ViewDidDisplay或viewdidload方法,使用从源VC传递的数组,并将其用作该第二个VC中的表视图的数据源
我希望这是有道理的。:-) 删除segue并添加情节提要id
删除segue并添加情节提要id
试试这个,它会帮助你:- 可以使用情节提要将数据从一个视图控制器发送到另一个视图控制器 例如 此处,NextController是您要转到的控制器类名。selectedCategory是您在NextController上声明的数组名 你可以发送任何东西数组字典,图像,Int值等 NextControllerStoryBoard\u id是您在该控制器的故事板上声明的id
希望这将帮助你尝试一下这将帮助你:- 可以使用情节提要将数据从一个视图控制器发送到另一个视图控制器 例如 此处,NextController是您要转到的控制器类名。selectedCategory是您在NextController上声明的数组名 你可以发送任何东西数组字典,图像,Int值等 NextControllerStoryBoard\u id是您在该控制器的故事板上声明的id
希望这将对您有所帮助错误在
loadItems
中。错误在loadItems
中。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let next = self.storyboard?.instantiateViewController(withIdentifier: "NextControllerStoryBoard_id")as! NextController
next.selectedCategory = categoryArray[indexPath.row]
self.navigationController?.pushViewController(next, animated: true) }