Swift UITableView:如何从JSON加载数据 [英] Swift UITableView: How to Load data from JSON

查看:145
本文介绍了Swift UITableView:如何从JSON加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的初学者,希望为我的第一个应用程序提供一些帮助.希望我能很好地解释它.我正在开发和应用程序,它正在从JSON文件加载信息.你们当中有人知道如何将这些信息填充到UI表格视图单元格中吗?我已经开发了3个视图控制器,在第一个中,我有一个按钮,用户必须按一下该按钮,然后将打开第二个Tableview控制器.我看了教程如何填充它,但似乎不起作用.第三个是Table View Cells.让我告诉你:

I am beginner in Swift and would like some help for my first application.I hope that I can explain it well. I am developing and app which is loading information from a JSON File. Does someone of you know how can I populate this information into a UI Table View Cells. I have developed 3 view controllers, in the first one I have a button, which the user has to press and the 2nd Tableview controller will be opened. I have watched tutorials how to populate it but it seems that it doesn't work. The 3rd one is the Table View Cells.let me show you:

class TableViewController: UITableViewController {
@IBOutlet weak var Bar: UIToolbar!
var TableData:Array< String > = Array < String >()
let ImageList = ["",""]
var TitleList = ["",""]
let DescriptionList = ["",""]

我必须在单元格中显示图像,标题和描述. 这是JSON文件:

I have to display in the cells Image, Title and Description. here is the JSON File:

 {
 "fruits" : [
 {
 "Name" : "Fruit1",
 "Picture":"http://www.starpropertiesindia.com/blog/wp-   content/uploads/2016/08/kochi1.jpg",
"Description":"",
},

  {
 "Name" : "Fruit2",
 "Picture":"http://www.starpropertiesindia.com/blog/wp-content/uploads/2016/08/kochi1.jpg",
 "Description":"",

},

如果有人建议我如何继续,我将非常感激.

I would be very thankful if someone advice me how to continue..

准备在新视图中进行搜索:

Prepare for segue in new view:

@IBOutlet weak var CellDescription: UILabel!
@IBOutlet weak var CellImage: UIImageView!
@IBOutlet weak var CellTitle: UILabel!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

推荐答案

首先,请勿将多个数组用作数据源.它们非常容易出错,因为您有责任使项目数量保持同步.

First of all, don't use multiple arrays for the data source. They are quite error-prone because you are responsible to keep the number of items in sync.

  • 由于Swift是一种面向对象的语言,因此使用自定义结构作为模型

  • Since Swift is an object-oriented language use a custom struct as model

struct Fruit {
  let name : String
  let imageURL : NSURL
  let description : String
}

  • 声明一个空的Fruit Swift数组作为数据源数组.基本上总是使用始终的Swift本机集合类型(而不是NSArrayNSDictionary),因为它们包含类型信息.

  • Declare an empty Swift array of Fruit as data source array. Basically use always Swift native collection types (rather than NSArray and NSDictionary) because they contain the type information.

    var fruits = [Fruit]()
    

  • 创建一个函数以解析JSON并重新加载表视图.该代码假定JSON文件名为jsonFile.json,并且位于应用程序捆绑包中.此外,它使用SwiftyJSON库.

  • Create a function to parse the JSON and reload the table view. The code assumes that the JSON file is named jsonFile.json and is located in the application bundle. Further it uses the SwiftyJSON library.

    func parseFruits() {
      guard let url = NSBundle.mainBundle().URLForResource("jsonFile", withExtension: "json"), jsonData = NSData(contentsOfURL: url) else {
        print("Error finding JSON File")
        return
      }
    
      let jsonObject = JSON(data: jsonData)
    
      let fruitArray = jsonObject["fruits"].arrayValue
      for aFruit in fruitArray {
        let name = aFruit["Name"].stringValue
        let imageURL = aFruit["Picture"].stringValue
        let description = aFruit["Description"].stringValue
    
        let fruit = Fruit(name: name, imageURL: NSURL(string:imageURL)!, description:description)
        fruits.append(fruit)
      }
    
      self.tableView.reloadData()
    }
    

  • 中的
  • 调用解析函数

  • in viewWillAppear call the parse function

    override func viewWillAppear() {
      super.viewWillAppear()
      parseFruits()
    }
    

  • 这些是表视图数据源委托方法,假定单元格的标识符为Cell并且单元格的样式为Right DetailSubtitle

  • These are the table view data source delegate methods assuming the identifier of the cell is Cell and the style of the cell is Right Detail or Subtitle

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return fruits.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
      let fruit = fruits[indexPath.row]
      cell.textLabel!.text = fruit.name
      cell.detailTextLabel?.text = fruit.description
      // add code to download the image from fruit.imageURL
      return cell
    }
    

  • 在Swift 4中,一切变得更短,更方便.最重要的变化是删除SwiftyJSON并使用Decodable

    In Swift 4 everything became much shorter and more convenient. The most significant change is to drop SwiftyJSON and use Decodable

    struct Fruit : Decodable {
       let name : String
       let imageURL : URL
       let description : String
    }
    
    func parseFruits() {
        let url = Bundle.main.url(forResource:"jsonFile", withExtension: "json")!
        let jsonData = try! Data(contentsOfURL: url)
        self.fruits = try! JSONDecoder().decode([Fruit].self, from: jsonData)
        self.tableView.reloadData()
    }
    

    这篇关于Swift UITableView:如何从JSON加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆