如何获取所选行的索引路径Swift4 JSON

时间:2017-08-24 23:24:27

标签: json swift4 detailview indexpath

我正在尝试使用此示例JSON https://api.myjson.com/bins/18qzq5中的信息获取详细信息视图中的标签,我能够填充tableView,但无法获取行的indexPath并且在detailView中我是收到错误"在解包一个Optional值"时意外地发现了nil。我列出的代码如下: *顺便说一下,我正在使用swift Decoder

[
  {
    "name": "New York",
    "state": "New York",
    "detail": "The largest city in the US"
  },
  {
    "name": "Los Angeles",
    "state": "California",
    "detail": "Second largest city in the US"
  }
]

tableView的ViewController

import UIKit

struct City: Codable {
    let name: String?
    let state: String?
    let detail: String?
}

class TableVC: UIViewController {

var citiesList: [City] = []
@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    let jsonString = "https://api.myjson.com/bins/18qzq5"

    guard let url = URL(string: jsonString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in

        guard let data = data else {return}

        do {
            let cities = try JSONDecoder().decode([City].self, from: data)

            if cities != nil {
                self.citiesList = cities

            }else{
                print("it's nil")
            }
            print(self.citiesList)

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        } catch let jsonErr{
            print("error serializing json:", jsonErr)
        }

    }.resume()
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let detailVC = segue.destination as? DetailTaskVC
        let city = sender as AnyObject as? City
        detailVC?.city = city
}

}

extension TableVC: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = citiesList[indexPath.row].name
    return cell
}
}

extension TableVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "toDetail", sender: citiesList[indexPath.row])
}
}

DetailViewController

import UIKit

class DetailTaskVC: UIViewController {

@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!

var city: City!

override func viewDidLoad() {
    super.viewDidLoad()

    self.nameLabel?.text = city.name //Unexpectedly found nil while unwrapping an Optional value
    self.stateLabel?.text = city.state
    self.detailLabel?.text = city.detail

}
}

希望你们可以帮助我解决这个问题,或者也许在网上有一个教程,你们可以指出我,因为我经常搜索并没有积极的结果。

1 个答案:

答案 0 :(得分:0)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let detailVC = segue.destination as? DetailTaskVC
    let city = sender as AnyObject as? City
    detailVC?.city = city
}

使用sender as? City代替sender as AnyObject as? City。您不能将结构转换为AnyObject。