【问题标题】:tableView Cell not displaying data, What's the issue? (Swift 3)tableView Cell 不显示数据,这是什么问题? (斯威夫特 3)
【发布时间】:2017-06-02 14:04:20
【问题描述】:

所以我有一个视图控制器来解析一些比特币价格数据。该函数成功响应并解析数据,但我似乎无法让它显示在 tableView 中。

我已经通过测试单元测试了插座和身份,确实工作。

我做错了什么?

代码:`

import UIKit
import Alamofire
import AlamofireObjectMapper
import ObjectMapper

class Response: Mappable{
    var data: [Amount]?

 required init?(map: Map){

}
    func mapping(map: Map) {
    data <- map["data"]
   }
}

class Amount: Mappable {
    var data : String?

    required init?(map: Map){

}
    func mapping(map: Map) {
    data <- map["data.amount"]
   }
}

class ViewController: UIViewController, UITableViewDelegate, 
UITableViewDataSource {
    var mount = [String]()
    var am = [String]()



    @IBOutlet var tableView: UITableView!


func Call_bitcoin() {
    let url = "https://api.coinbase.com/v2/prices/BTC-USD/buy"
    Alamofire.request(url).responseObject{ (response: DataResponse<Amount>) in
        let mount = response.result.value
        let am = mount?.data


        self.tableView.reloadData()

        return


    }
}





    override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    tableView.delegate = self
    tableView.dataSource = self
    Call_bitcoin()
}


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


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("You tapped cell number \(indexPath.row).")
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    print(am)
    cell.textLabel?.text = am[indexPath.row]
    return cell
}

}

`

【问题讨论】:

  • 你设置tableView.dataSource = selftableView.delegate = self了吗?
  • 如果你的单元格不可见可能am.count返回0

标签: ios swift uitableview cocoa-touch alamofire


【解决方案1】:

您想在 Call_bitcoin() 函数中添加元素,但您做错了。您已经创建了var am = [String]()。所以你不需要使用let am = mount?.data。您可以将数据添加到已创建的 am 变量中。您需要更改 Call_bitcoin() 函数中的一些代码行:

发件人:

let mount = response.result.value
let am = mount?.data

收件人:

let mount = response.result.value
am.append(mount?.data) // This part should be set by your 'mount?.data' value type

【讨论】:

  • 谢谢!!这基本上是正确的。 Xcode 对我大喊大叫,把它变成了这样:self.am.append((mount?.data)!)
【解决方案2】:

你的 JSON 没有返回数组,它有字典。这就是你得到的原因

am.count = 0

首先解决您的数据并将数据放入数组中。

 {"data":{"amount":"2414.88","currency":"USD"},"warnings":[{"id":"missing_version","message":"Please supply API version (YYYY-MM-DD) as CB-VERSION header","url":"https://developers.coinbase.com/api#versioning"}]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2017-03-24
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多