我遇到了同樣的問題here我還沒有想出如何將正確的數據從TableViewController傳遞到另一個ViewController。我從JSON獲取數據我擁有我需要的所有內容,但通過選擇顯示最後一行中的數據的任何行數據。我需要獲取有關我選擇TableViewController的確切行的信息。將來自UITableViewController中選定單元的「正確」數據傳遞給ViewController
import UIKit
class TableViewController: UITableViewController {
var TableData:Array<String> = Array <String>()
func getData(_ link: String) {
let url: URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _: Data = data , let _: URLResponse = response , error == nil else {
return
}
self.extractJSON(data!)
})
task.resume()
}
func extractJSON(_ data: Data) {
let json: Any?
do {
json = try JSONSerialization.jsonObject(with: data, options: [])
} catch {
return
}
guard let dataList = json as? NSArray else {
return
}
if let countriesList = json as? NSArray {
for i in 0 ..< dataList.count {
if let countriesObj = countriesList[i] as? NSDictionary {
if let countryName = countriesObj["country"] as? String {
if let countryCode = countriesObj["code"] as? String {
TableData.append(countryName + " [" + countryCode + "]")
UserDefaults.standard.set(String(describing: countryName), forKey: "name")
UserDefaults.standard.set(String(describing: countryCode), forKey: "code")
UserDefaults.standard.synchronize()
}
}
}
}
}
DispatchQueue.main.async(execute: {self.doTableRefresh()})
}
func doTableRefresh() {
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
getData("http://www.kaleidosblog.com/tutorial/tutorial.json")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return TableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = TableData[indexPath.row]
return cell
}
}
您可以使用tableViewDidSelectRowAtIndexPath,讓您的數據,並把它傳遞給在vc –