gpt4 book ai didi

ios - 快速将数据从 tableview 传递到 viewController

转载 作者:行者123 更新时间:2023-12-04 12:18:54 27 4
gpt4 key购买 nike

我有一个 tableview 使用 Alamofire 从 php json 加载数据,它在 tableview 上加载完美,现在我尝试将数据传递给第二个 viewController 以显示更多详细信息,我遇到了这个错误,提示无法在范围内找到数据

func getUsers() {
AF.request(SiteUrl).validate().responseJSON { response in
switch response.result {
case .success:
print("Validation Successful)")

if let json = response.data {
do{
let jsonData = try JSON(data: json)
self.data = jsonData.arrayValue
self.tableView.reloadData() // we are already on the main thread
//print("DATA PARSED: \(jsonData)")
}
catch {
print("JSON Error", error)
}
}
case .failure(let error):
print(error)
}
}
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell

let item = data[indexPath.row]
customCell.AdTitle?.text = item["title"].string
customCell.AdDate?.text = item["time"].string

let imageUrl = item["document"].string
let url = NSURL(string:("https://qateef-ads.co/uploads/" + imageUrl!))
customCell.AdImage.sd_setImage(with: url as URL?, placeholderImage: UIImage(named: "placeholder.png"))

return customCell
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

let vc = storyboard?.instantiateViewController(withIdentifier: "DetailsViewController") as? DetailsViewController
self.navigationController?.pushViewController(vc!, animated: true)
vc?.imageView = UIImage(named: url)
vc?.AdTitle = item["title"].string
}
如何将数据从第二个 View 传递?

最佳答案

我不确定我是否理解您的问题到底是什么。但是如果您需要访问第二个 View Controller 上的数据,最简单的方法是将该数据注入(inject) DetailsViewController您在选择单元格时实例化。
但首先您需要创建该属性:

class DetailsViewController: UIViewController {
var data: JSON?

...

}
然后在实例化该 View Controller 时:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

guard let vc = storyboard?.instantiateViewController(withIdentifier: "DetailsViewController") as? DetailsViewController else { return }
vc.data = data[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
现在您可以在 DetailsViewController 上使用该数据。从 json 响应中提取您需要的任何信息:
class DetailsViewController: UIViewController {

...

override viewDidLoad() {
super.viewDidLoad()
let title = data["title"]
...
}

}

关于ios - 快速将数据从 tableview 传递到 viewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65665182/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com