在我的 tableview.swift 中,我将用户配置文件加载到单元格中。当用户选择这些单元格之一时,他们将被重定向到 mainProfile.swift,在那里他们可以看到所选的用户配置文件。在阅读了几篇文章后,我在 tableview.swift 中设置了这段代码,但它仍然没有将从 tableview 的单元格中捕获的数据传递到 mainProfile
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
以仅执行 segue:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "mainProfile", sender: self)
}
(或者完全删除这个方法,直接将转场添加到 Storyboard中的单元格原型(prototype)。)
然后,将 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]
}
}
关于ios - 数据传递失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41556736/