我试图将我的对象传递到新视图,并且无法传递数据。它一直返回零。我尝试使用协议和委托来做到这一点,并且它也一直返回nil。我决定只在didSelectRowAt中传递数据,但是在加载新视图时,它不会显示正确的信息。它返回nil。我试图通过仅传递名称来测试它。我不确定在这里我到底在做什么错。 currentUser和name都返回nil
class HomeVC: {
var sortedArr = [Response.Users]()
func showDetail() {
let modalViewController = DetailView()
modalViewController.modalPresentationStyle = .overCurrentContext
present(modalViewController, animated: true) {
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! UserTableCell
let arr = sortedArr[indexPath.row]
cell.titleLabel.text = arr.fullName
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let arr = sortedArr[indexPath.row]
let detailVC = DetailView()
detailVC.currentUser = [arr]
detailVC.name = arr.fullName
showDetail()
}
}
class DetailView: UIViewController {
var currentUser: [Response.Users]!
var name: String?
override func viewDidLoad() {
print(name)
print(currentUser)
super.viewDidLoad()
}
}
答案 0 :(得分:1)
您在didSelectRowAt内部创建了一个对象,然后调用方法showDetail()
,在该方法中,您将创建一个相同方法的新实例,然后在最后一个未设置与之相关的值的实例中进行推送
currentUser和名称,然后如何获取值
更改didSelectRowAt方法
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let arr = sortedArr[indexPath.row]
let detailVC = DetailView()
detailVC.currentUser = [arr]
detailVC.name = arr.fullName
detailVC.modalPresentationStyle = .overCurrentContext
present(detailVC, animated: true) {
}
}
答案 1 :(得分:1)
您只需要将didVC方法的detailVC对象传递给函数showDetail()的参数。
请尝试一下
class HomeVC: {
var sortedArr = [Response.Users]()
func showDetail(detailVC: DetailView) {
detailVC.modalPresentationStyle = .overCurrentContext
present(detailVC, animated: true) {
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! UserTableCell
let arr = sortedArr[indexPath.row]
cell.titleLabel.text = arr.fullName
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let arr = sortedArr[indexPath.row]
let detailVC = DetailView()
detailVC.currentUser = [arr]
detailVC.name = arr.fullName
showDetail(detailVC: detailVC)
}
}
class DetailView: UIViewController {
var currentUser: [Response.Users]!
var name: String?
override func viewDidLoad() {
print(name)
print(currentUser)
super.viewDidLoad()
}
}