我有一个 TableView 显示来自存储在数组 var lastDayChange = [String]()
中的 JSON 的数据,如果结果低于 0 (如 -1 或 -2 等),如果结果高于 0(如 1 或 2 等)则为绿色;如下图所示:
我在同一个 ViewController.swift 文件中创建了这个类:
struct Coin: Codable {
let symbol : String
let price_usd : String
let percent_change_24h : String}
这是我的表格 View :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BitcoinTableViewCell", for: indexPath) as! BitcoinTableViewCell
let lineNumbers = Array(1...200)
cell.lineNumberLable.text = " \(lineNumbers[indexPath.row]) -"
cell.coinNameLable.text = sympolsCoin[indexPath.row]
cell.priceLable.text = "$" + priceUSDcoin[indexPath.row]
cell.lastDayChange.text = lastDayChange[indexPath.row] + "%"
//cell.coinLogoImage.image = UIImage(named : cryptoCurrencyImage[indexPath.row])
return cell
}
还有这个带有数组的 json 来保存数据:
var coins = [Coin]()
var sympolsCoin = [String]()
var priceUSDcoin = [String]()
var lastDayChange = [String]()
func getCoinData() {
let jsonURL = "https://api.coinmarketcap.com/v1/ticker/"
let url = URL(string: jsonURL)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do {
self.coins = try JSONDecoder().decode([Coin].self, from: data!)
for info in self.coins {
self.sympolsCoin.append(info.symbol)
self.priceUSDcoin.append(info.price_usd)
self.lastDayChange.append(info.percent_change_24h)
DispatchQueue.main.async {
self.coinTableView.reloadData()
}
//self.coinTableView.reloadData()
}
}catch {
print("Error is : \n\(error)")
}
}.resume()
}
最佳答案
你可以在 tableView(_:cellForRowAt:)
中这样做:
cell.lastDayChange.textColor = Float(lastDayChange[indexPath.row])! >= 0 ? .green : .red
首先,您在 indexPath
中获取 lastDayChange
项,并将其从 String
转换为 Int
, 并根据该项目的值设置标签颜色。
关于ios - 如何更改 TableView 中的标签文本颜色(数据存储在数组中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48049171/