简体   繁体   中英

Creating TableViews in Swift with an Array

I'm attempting to use the result of one Rest call as an input for my TableView. I've got an array named GamesList[String] that is synthesized in the viewDidLoad() function. This is the viewDidLoad() fuction:

override func viewDidLoad() {
    super.viewDidLoad()

    getState() { (json, error) -> Void in
        if let er = error {
            println("\(er)")
        } else {
            var json = JSON(json!);
            print(json);

            let count: Int = json["games"].array!.count
            println("found \(count) challenges")

            for index in 0...count-1{
                println(index);
                self.GamesList.append(json["games"][index]["game_guid"].string!);
            }
        }
    }
}

The problem is that the functions for filling the TableView get executed before my GamesList array is filled up. These are the functions that fill the TableView:

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Game", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = GamesList[indexPath.row]
    cell.detailTextLabel?.text = GamesList[indexPath.row]
    return cell
}

How do I force the tables to get filled up (refreshed) after my array has been filled?

use self.tableView.reloadData() after you append your values

 getState() { (json, error) -> Void in
        if let er = error {
            println("\(er)")
        } else {
            var json = JSON(json!);
            print(json);

            let count: Int = json["games"].array!.count
            println("found \(count) challenges")

            for index in 0...count-1{
                println(index);
                self.GamesList.append(json["games"][index]["game_guid"].string!);
            }
            dispatch_async(dispatch_get_main_queue()) {
                self.tableView.reloadData()
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM