Populate UITableView with NSDictionary JSON in Swift

后端 未结 1 1732
耶瑟儿~
耶瑟儿~ 2021-01-16 07:24

I am Fresher.I called API and i am getting request and Response of data.But,I dont know how to populate data from NSDictionary to TableviewCell.Can anyone help me.

C

相关标签:
1条回答
  • 2021-01-16 07:44
    let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
    
    if jsonData {
    // process jsonData
    
    var arrayofBOOKs: NSArray = jsonData["ListOfBooks"] as NSArray
    for elem: AnyObject in arrayofBOOKs {
    let name = elem["Book_name"] as String
    
    println("Book_name: \(name)")
    // here add the string to array 
     items.addObject(name)
    }
    tableView.reloadData
    
    } else {
    // couldn't load JSON, look at error
    }
    

    Here are the steps to follow:

    Step-1

    Open the ViewController.swift class and add a new tableview instance variable below the class declaration

    @IBOutlet
    var tableView: UITableView!
    

    Step-2

    To conform to the UITableViewDelegate and UITableViewDataSource protocol just add them seperated by colons afterUIViewController in the class declaration

    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    override func viewDidLoad() {
        super.viewDidLoad()
    
        var  items = NSMutableArray()
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    
    
    }
    

    step-3

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  items.count;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
    
        cell.textLabel?.text =  items[indexPath.row]
    
        return cell
    }
    
      func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("You selected cell #\(indexPath.row)!")
    }
    
    0 讨论(0)
提交回复
热议问题