gpt4 book ai didi

swift、numberOfRowsInSection 和 cellForRowAt 函数不返回值

转载 作者:行者123 更新时间:2023-11-30 11:36:16 25 4
gpt4 key购买 nike

我有一个问题,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
}
}

最佳答案

你必须调用重新加载

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
}

关于swift、numberOfRowsInSection 和 cellForRowAt 函数不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49737628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com