【问题标题】:how to populate data in UITableView ? swift如何在 UITableView 中填充数据?迅速
【发布时间】:2015-05-11 09:16:43
【问题描述】:

我已经设法使用 swift JSON 从 JSON 中检索数据,但是当我尝试填充 tableview 时遇到了问题。我是 iOS 开发的新手,所以请多多包涵。如果您能提供帮助或提供一些想法,我将不胜感激?

代码如下:

 override func viewDidLoad(){
 super.viewDidLoad()
 getContactListJSON()
 }

 func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
    let json = JSON(data: data)
    let contactsArray = json.arrayValue

    dispatch_async(dispatch_get_main_queue(), {
        for contacts in contactsArray
        {
            let id = contacts["id"].stringValue
            let name = contacts["name"].stringValue
            println( "id: \(id) name: \(name)" )
        }
    })
}
task.resume()
}

【问题讨论】:

    标签: ios uitableview swift swifty-json


    【解决方案1】:

    这是您的完整代码:

    import UIKit
    
    class TableViewController: UITableViewController {
    
    var tableName = [String]()
    var tableID = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
        getContactListJSON()
    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func getContactListJSON(){
        let urlString = "http://jsonplaceholder.typicode.com/users"
        let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
        let url = NSURL( string: urlEncodedString!)
        var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
            let json = JSON(data: data)
            let contactsArray = json.arrayValue
    
            dispatch_async(dispatch_get_main_queue(), {
                for contacts in contactsArray
                {
                    let id = contacts["id"].stringValue
                    let name = contacts["name"].stringValue
                    println( "id: \(id) name: \(name)" )
                    self.tableName.append(name)
                    self.tableID.append(id)
                }
                dispatch_async(dispatch_get_main_queue(),{
                    self.tableView.reloadData()
                })
            })
        }
        task.resume()
    }
    
    // MARK: - Table view data source
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableName.count
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
    
        // Configure the cell...
        cell.id.text = tableID[indexPath.row]
        cell.name.text = tableName[indexPath.row]
        return cell
    
        }
    }
    

    HERE 正在为您使用自定义单元格的示例项目。

    【讨论】:

      【解决方案2】:

      首先声明一个名为contactArray的局部变量NSArray。

          override func viewDidLoad(){
                           super.viewDidLoad()
      
                           getContactListJSON()
      
      
                           }
      
      
          //Code for downloading data
           func getContactListJSON(){
                              let urlString = "http://jsonplaceholder.typicode.com/users"
                              let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
                              let url = NSURL( string: urlEncodedString!)
                              var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
                                  let json = JSON(data: data)
                                  self.contactsArray = json.arrayValue
      
                                  dispatch_async(dispatch_get_main_queue(), {
                                      [self.tableView reloadData]
                                  })
                              }
                              task.resume()
                              }
      
      func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                          return self.contactsArray.count;
                      }
      
      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
                          var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
                          var contacts:NSDictionary = self.contactsArray[indexPath.row];
                          cell.textLabel?.text =   contacts["name"].stringValue
                          //.......
                          //.......
      
                          return cell
                      }
      

      【讨论】:

      • 嗨,感谢您的帮助,但我在这一行遇到错误 self.contactsArray = json.arrayValue "Cannot assign a value of type '[JSON]" to a value of type 'NSMutableArray'
      • 另一个错误:“找不到接受类型为 '(array: [JSON]) 的参数列表的类型 'NSMutableArray' 的初始化程序”
      • 不,没用。又出错了。我也试过 self.contactsArray = NSArray(array: json.arrayValue) 也没有用。
      【解决方案3】:

      这是一段代码。

      var dataArray = [String]()
      
      override func viewDidLoad(){
       super.viewDidLoad()
       getContactListJSON()
       }
      
       func getContactListJSON(){
      let urlString = "http://jsonplaceholder.typicode.com/users"
      let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
      let url = NSURL( string: urlEncodedString!)
      var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
          let json = JSON(data: data)
          let contactsArray = json.arrayValue
      
          dispatch_async(dispatch_get_main_queue(), {
              for contacts in contactsArray
              {
                  let id = contacts["id"].stringValue
                  let name = contacts["name"].stringValue
                  println( "id: \(id) name: \(name)" )
                  self.dataArray.append(name)
              }
              self.tableView.reloadData()
          })
      }
      task.resume()
      }
      

      我在这里取名字。如果你也想显示 id,那么为它创建一个模型类。

      【讨论】:

      • 感谢您的帮助,但其他示例更清楚。谢谢!
      • 为什么 dispatch_async 被调用两次?因为它,我的索引超出范围
      • 你说得对,不需要两个 dipatch_async。对不起,我的错误,现在更正。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多