【问题标题】:Swift - How can I use a dictionary to give text for tableView cells?Swift - 如何使用字典为 tableView 单元格提供文本?
【发布时间】:2019-01-30 21:34:54
【问题描述】:

我有以下 JSON 文件:

[
{
"countryName": "Afghanistan",
"continent": "Asia",
"population": 34656032,
"currency": "Afghani"
},
{
"countryName": "Albania",
"continent": "Europe",
"population": 2876591,
"currency": "Lek"
},
{
"countryName": "Bulgaria",
"continent": "Europe",
"population": 7050034,
"currency": "Lev"
},
{
"countryName": "Finland",
"continent": "Europe",
"population": 5517887,
"currency": "Euro"
},
{
"countryName": "Iceland",
"continent": "Europe",
"population": 350710,
"currency": "Icelandic Krona"
},
{
"countryName": "Japan",
"continent": "Asia",
"population": 126672000,
"currency": "Yen"
},
{
"countryName": "Oman",
"continent": "Middle East",
"population": 4424762,
"currency": "Rial"
},
{
"countryName": "South Africa",
"continent": "Africa",
"population": 57725600,
"currency": "South African Rand"
},
{
"countryName": "Uruguay",
"continent": "South America",
"population": 3444006,
"currency": "Uruguayan Peso"
},
{
"countryName": "Venezuela",
"continent": "South America",
"population": 31568179,
"currency": "Bolivar Soberano"
}
]

使用 SwiftyJson 将其解析到我的项目中后,我希望 tableView 中的每个单元格都有“countryName”的标题,所以有以下代码:

import UIKit

class ViewController: UITableViewController {

var countries = [[String: String]]()
var numberOfCountries = 0

override func viewDidLoad() {
    super.viewDidLoad()

    title = "Select country"

    if let jsonPath = Bundle.main.path(forResource: "Countries", ofType: "json") {

        if let data = try? String(contentsOfFile: jsonPath) {

            print("data: \(data)")

            let json = JSON(parseJSON: data)

            parse(json: json)

            print("countries: \(countries)")

        } else {
            print("Unable to get contents of JSON file")
        }
    }

}

func parse(json: JSON) {
    for result in json.arrayValue {
        let countryName = result["countryName"].stringValue
        let continent = result["continent"].stringValue
        let population = result["population"].stringValue
        let currency = result["currency"].stringValue

        let obj = ["countryName": countryName, "continent": continent, "population": population, "currency": currency]

        countries.append(obj)
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let numberOfCountries = countries.count
    return numberOfCountries
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Country", for: indexPath)
    var cellTitle = ""

    for item in countries {
        cellTitle = item["countryName"] as! String
        print("cellTitle: \(cellTitle)")
    }

    cell.textLabel?.text = cellTitle
    return cell
}

但是,数组只是循环了十次不同的次数,委内瑞拉被选为每个 tableView 单元格的标题。

我的调试控制台出现如下:

countries: [["countryName": "Afghanistan", "continent": "Asia", "population": "34656032", "currency": "Afghani"], ["countryName": "Albania", "continent": "Europe", "population": "2876591", "currency": "Lek"], ["countryName": "Bulgaria", "continent": "Europe", "population": "7050034", "currency": "Lev"], ["countryName": "Finland", "continent": "Europe", "population": "5517887", "currency": "Euro"], ["countryName": "Iceland", "continent": "Europe", "population": "350710", "currency": "Icelandic Krona"], ["countryName": "Japan", "continent": "Asia", "population": "126672000", "currency": "Yen"], ["countryName": "Oman", "continent": "Middle East", "population": "4424762", "currency": "Rial"], ["countryName": "South Africa", "continent": "Africa", "population": "57725600", "currency": "South African Rand"], ["countryName": "Uruguay", "continent": "South America", "population": "3444006", "currency": "Uruguayan Peso"], ["countryName": "Venezuela", "continent": "South America", "population": "31568179", "currency": "Bolivar Soberano"]]
cellTitle: Afghanistan
cellTitle: Albania
cellTitle: Bulgaria
cellTitle: Finland
cellTitle: Iceland
cellTitle: Japan
cellTitle: Oman
cellTitle: South Africa
cellTitle: Uruguay
cellTitle: Venezuela
cellTitle: Afghanistan
cellTitle: Albania
cellTitle: Bulgaria
cellTitle: Finland
cellTitle: Iceland
cellTitle: Japan
cellTitle: Oman
cellTitle: South Africa
cellTitle: Uruguay
cellTitle: Venezuela
cellTitle: Afghanistan
cellTitle: Albania
cellTitle: Bulgaria
cellTitle: Finland
cellTitle: Iceland
cellTitle: Japan
cellTitle: Oman
cellTitle: South Africa
cellTitle: Uruguay
cellTitle: Venezuela
cellTitle: Afghanistan
cellTitle: Albania
cellTitle: Bulgaria
cellTitle: Finland
cellTitle: Iceland
cellTitle: Japan
cellTitle: Oman
cellTitle: South Africa
cellTitle: Uruguay
cellTitle: Venezuela
cellTitle: Afghanistan
cellTitle: Albania
cellTitle: Bulgaria
cellTitle: Finland
cellTitle: Iceland
cellTitle: Japan
cellTitle: Oman
cellTitle: South Africa
cellTitle: Uruguay
cellTitle: Venezuela
cellTitle: Afghanistan
cellTitle: Albania
cellTitle: Bulgaria
cellTitle: Finland
cellTitle: Iceland
cellTitle: Japan
cellTitle: Oman
cellTitle: South Africa
cellTitle: Uruguay
cellTitle: Venezuela
cellTitle: Afghanistan
cellTitle: Albania
cellTitle: Bulgaria
cellTitle: Finland
cellTitle: Iceland
cellTitle: Japan
cellTitle: Oman
cellTitle: South Africa
cellTitle: Uruguay
cellTitle: Venezuela
cellTitle: Afghanistan
cellTitle: Albania
cellTitle: Bulgaria
cellTitle: Finland
cellTitle: Iceland
cellTitle: Japan
cellTitle: Oman
cellTitle: South Africa
cellTitle: Uruguay
cellTitle: Venezuela
cellTitle: Afghanistan
cellTitle: Albania
cellTitle: Bulgaria
cellTitle: Finland
cellTitle: Iceland
cellTitle: Japan
cellTitle: Oman
cellTitle: South Africa
cellTitle: Uruguay
cellTitle: Venezuela
cellTitle: Afghanistan
cellTitle: Albania
cellTitle: Bulgaria
cellTitle: Finland
cellTitle: Iceland
cellTitle: Japan
cellTitle: Oman
cellTitle: South Africa
cellTitle: Uruguay
cellTitle: Venezuela

我怎样才能只循环这个数组一次,在每个实例中选择“countryName”的值,然后将其用作我的单元格标题?

感谢任何可以提供帮助的人。这个让我发疯了!

【问题讨论】:

  • 可能您的parse() 方法被多次调用。在发送解析请求时重置countriescountries. = []

标签: ios swift uitableview dictionary


【解决方案1】:

您似乎误解了表格视图的工作原理。

cellForRowAt 每行调用一次countries 次)。您必须为传递的indexPath 获取数据源数组中的值并更新 UI:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Country", for: indexPath)
    let country = countries[indexPath.row]
    cell.textLabel?.text = country["countryName"]!
    return cell
}

最有效的解决方案是使用Codable 协议将 JSON 解码为结构(并丢弃 SwiftyJSON)

struct Country : Decodable {
    let countryName, continent, currency : String
    let population : Int
}

var countries = [Country]()

override func viewDidLoad() {
    super.viewDidLoad()

    title = "Select country"

    // If the code crashes in one of the following lines you made a design mistake
    let jsonURL = Bundle.main.url(forResource: "Countries", withExtension: "json")!
    let data = try! Data(contentsOf: jsonURL)
    countries = try! JSONDecoder().decode([Country].self, from: data)
    tableView.reloadData()
}

...

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Country", for: indexPath)
    let country = countries[indexPath.row]
    cell.textLabel?.text = country.countryName
    return cell
}

【讨论】:

    【解决方案2】:

    对于表格视图需要创建的每个单元格调用一次方法tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)

    这意味着在您的实现中,您不必循环访问数据,而是返回表视图现在要求的一项。参数indexPath 指示您应该为哪一行返回一个单元格。

    由于您的数据是字典,处理此问题的一种可能方法是将其键存储为数组,然后使用属性indexPath.row 访问与行对应的键。

    【讨论】:

      【解决方案3】:

      那么你为什么要循环遍历单元格内的所有项目以获取索引路径处的行。重点是使用数组上的索引路径为countries[indexPath.row]["countryName"]

      但还有一些其他的东西可能有点……用起来很奇怪。也许从研究以下重构开始。我已经删除了映射并使用原生工具来解析 JSON,只是为了让它现在更加独立。

      class ViewController: UITableViewController {
      
          private var countries: [[String: Any]]?
      
          override func viewDidLoad() {
              super.viewDidLoad()
      
              title = "Select country"
              reloadData()
          }
      
          private func reloadData() {
              if let jsonPath = Bundle.main.path(forResource: "Countries", ofType: "json") {
                  if let data = FileManager.default.contents(atPath: jsonPath) {
      
                      if let stringRepresentation = String(data: data, encoding: .utf8) {
                          print("Data: \(stringRepresentation)")
                      } else {
                          print("Could not represent data as string (\(data.count) bytes) ")
                      }
      
      
                      if let countries = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [[String: Any]] {
                          self.countries = countries
                          print("countries: \(countries)")
                      } else {
                          print("Could not parse countries")
                      }
      
                  } else {
                      print("Unable to get contents of JSON file")
                  }
              }
              tableView.reloadData()
          }
      
          override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
              return countries?.count ?? 0
          }
      
          override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              if let descriptor = self.countries?[indexPath.row] {
                  let cell = tableView.dequeueReusableCell(withIdentifier: "Country", for: indexPath)
                  cell.textLabel?.text = descriptor["countryName"] as? String
                  return cell
              } else {
                  // No data!?
                  return UITableViewCell()
              }
          }
      
      }
      

      但就映射而言,至少拥有自己的结构是件好事。在它之后,Swift 有一些不错的工具,比如compactMap,它将一个对象类型的数组转换为另一个对象类型。见以下代码:

      class ViewController: UITableViewController {
      
          struct Country {
              let name: String
              let continent: String?
              let population: Int
              let currency: String?
      
              init?(descriptor: [String: Any]) {
                  guard let name = descriptor["countryName"] as? String else {
                      return nil // We want at least the country name to be mandatory
                  }
                  self.name = name
                  self.continent = descriptor["continent"] as? String
                  self.population = (descriptor["population"] as? Int) ?? 0
                  self.currency = descriptor["currency"] as? String
              }
          }
      
          private var countries: [Country]?
      
          override func viewDidLoad() {
              super.viewDidLoad()
      
              title = "Select country"
              reloadData()
          }
      
          private func reloadData() {
              if let jsonPath = Bundle.main.path(forResource: "Countries", ofType: "json") {
                  if let data = FileManager.default.contents(atPath: jsonPath) {
      
                      if let stringRepresentation = String(data: data, encoding: .utf8) {
                          print("Data: \(stringRepresentation)")
                      } else {
                          print("Could not represent data as string (\(data.count) bytes) ")
                      }
      
      
                      if let countries = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [[String: Any]] {
                          self.countries = countries.compactMap { Country(descriptor: $0) }
                          print("countries: \(countries)")
                      } else {
                          print("Could not parse countries")
                      }
      
                  } else {
                      print("Unable to get contents of JSON file")
                  }
              }
              tableView.reloadData()
          }
      
          override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
              return countries?.count ?? 0
          }
      
          override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              if let country = self.countries?[indexPath.row] {
                  let cell = tableView.dequeueReusableCell(withIdentifier: "Country", for: indexPath)
                  cell.textLabel?.text = country.name
                  return cell
              } else {
                  // No data!?
                  return UITableViewCell()
              }
          }
      
      }
      

      【讨论】:

        【解决方案4】:

        你正在为每一行循环整个数组

        代替

        var cellTitle = ""
        
        for item in countries {
            cellTitle = item["countryName"] as! String
            print("cellTitle: \(cellTitle)")
        }
        
        cell.textLabel?.text = cellTitle
        

        试试

        cell.textLabel?.text = countries[indexPath.row]["countryName"] as! String
        

        【讨论】:

          猜你喜欢
          • 2015-07-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-20
          相关资源
          最近更新 更多