Ios 数据无法传递
在我的tableview.swift中,我将用户配置文件加载到单元格中。当用户选择其中一个单元格时,它们将被重定向到mainProfile.swift,在那里可以看到所选的用户配置文件。在阅读了几篇文章之后,我在tableview.swift中设置了这段代码,但它仍然没有将从tableview的单元格捕获的数据传递到mainProfile中Ios 数据无法传递,ios,swift,uitableview,uiviewcontroller,Ios,Swift,Uitableview,Uiviewcontroller,在我的tableview.swift中,我将用户配置文件加载到单元格中。当用户选择其中一个单元格时,它们将被重定向到mainProfile.swift,在那里可以看到所选的用户配置文件。在阅读了几篇文章之后,我在tableview.swift中设置了这段代码,但它仍然没有将从tableview的单元格捕获的数据传递到mainProfile中 var mainProfile: mainProfile? override func tableView(_ tableView: UITableView
var mainProfile: mainProfile?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user1 = self.users[indexPath.row]
mainProfile?.user2 = user1
print(mainProfile?.user2 as Any)
performSegue(withIdentifier: "mainProfile", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mainProfile" {
let viewControllerAccept = segue.destination as! mainProfile
let user2 = sender as Any?
viewControllerAccept.user2 = user2 as! User?
}
}
您应该简化
didSelectRowAt
,只执行以下步骤:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "mainProfile", sender: self)
}
(或者完全删除此方法,只需将segue直接添加到情节提要中的单元原型中。)
然后,更改prepare(segue:)
以使用indexPathForSelectedRow
来了解选择了哪一行:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mainProfile" {
let indexPath = tableView.indexPathForSelectedRow!
let viewController = segue.destination as! MainProfileViewController
viewController.user2 = users[indexPath.row]
}
}
顺便说一下,我更改了目标视图控制器类的名称,因为按照Cocoa命名约定,类应该始终以大写字母开头。显然,在你的情况下使用任何合适的类名。我不知道该如何感谢你!这个解决方案非常有效,再次感谢