swift,numberOfRowsInSection和cellForRowAt函数不返回值

时间:2018-04-09 16:34:57

标签: swift uitableview

我有一个问题,numberOfRowsInSection和cellForRowAt函数不返回值。我需要将来自coincap.io/front API的名称和价格返回到tableView。我试图将返回值更改为整数并且它工作正常,但无论如何我不能返回另一个值。

这是代码:

import UIKit
import Alamofire
import SwiftyJSON

class Currency : NSObject {
    var name : String!
    var price : Double!

    init(name : String, price : Double) {
        self.name = name
        self.price = price
    }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!
    let DATA_URL : String = "http://coincap.io/front"
    var currencies = [Currency]()
    var counter = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        getData(url: DATA_URL)
    }

    func getData(url: String) {
        Alamofire.request(url, method: .get).responseJSON { response in
            if response.result.isSuccess {
                print("Success! Got the data")
                let dataJSON : JSON = JSON(response.result.value!)
              // print(dataJSON)
                self.updateData(json: dataJSON)
            } else {
                print("Error \(String(describing: response.result.error))")
            }
        }
    }

    func updateData(json: JSON) {
        for (_, current) in json{
            currencies.append(Currency(name: current["long"].stringValue, price: current["price"].doubleValue))
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return NSInteger(counter)
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "currencyCell", for: indexPath)
        let current = currencies[indexPath.row]

        cell.textLabel?.text = current.name
        cell.detailTextLabel?.text = "\(current.price!)"
        return cell
    }
}

1 个答案:

答案 0 :(得分:0)

您必须致电重新加载

func getData(url: String) {
    Alamofire.request(url, method: .get).responseJSON { response in
        if response.result.isSuccess {
            print("Success! Got the data")
            let dataJSON : JSON = JSON(response.result.value!)
          // print(dataJSON)
            self.updateData(json: dataJSON)
            DispatchQueue.main.async {self.tableView.reloadData()}
        } else {
            print("Error \(String(describing: response.result.error))")
        }
    }
}

同时替换

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return NSInteger(counter)
}

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