You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TableView中根据数组内正负值修改标签文字颜色

Solution for Color-Coding Percentage Labels in UITableView

Hey there! Let's get your percentage labels colored correctly based on positive/negative values, while also cleaning up your code for better maintainability. Here's how to do it step by step:

1. Simplify Your Data Handling

Right now, you're using separate arrays (sympolsCoin, priceUSDcoin, lastDayChange) to store parts of your Coin data—this is unnecessary and can lead to data synchronization issues. Instead, use your existing coins array directly in cellForRowAt to access all the data you need.

2. Add Color Logic Based on Percentage Value

To set the text color, you'll need to convert the string-based percent_change_24h to a numeric type (like Double), then check if it's positive, negative, or zero. Always handle optional values here to avoid crashes if the string can't be converted to a number.

3. Fix the Data Fetching & Table Reload

Your current getCoinData method calls reloadData inside the loop over coins, which will refresh the table multiple times. Move this call outside the loop to refresh once after all data is loaded.

Modified Code

Updated cellForRowAt Method

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "BitcoinTableViewCell", for: indexPath) as! BitcoinTableViewCell
    let currentCoin = coins[indexPath.row]
    
    // Set row number (no need for a separate lineNumbers array)
    cell.lineNumberLable.text = " \(indexPath.row + 1) -"
    
    // Populate cell with coin data directly from the Coin struct
    cell.coinNameLable.text = currentCoin.symbol
    cell.priceLable.text = "$" + currentCoin.price_usd
    
    // Handle percentage label and color
    let percentageText = currentCoin.percent_change_24h
    cell.lastDayChange.text = "\(percentageText)%"
    
    // Convert string to Double to check value
    if let percentageValue = Double(percentageText) {
        if percentageValue > 0 {
            cell.lastDayChange.textColor = .green
        } else if percentageValue < 0 {
            cell.lastDayChange.textColor = .red
        } else {
            cell.lastDayChange.textColor = .black // Default for 0%
        }
    } else {
        // Fallback color if conversion fails
        cell.lastDayChange.textColor = .black
    }
    
    // cell.coinLogoImage.image = UIImage(named : cryptoCurrencyImage[indexPath.row])
    return cell
}

Updated getCoinData Method (Remove Unnecessary Arrays)

First, delete these unused arrays from your ViewController:

// Remove these lines—we don't need them anymore!
// var sympolsCoin = [String]()
// var priceUSDcoin = [String]()
// var lastDayChange = [String]()

Then update the data fetching method:

func getCoinData() {
    let jsonURL = "https://api.coinmarketcap.com/v1/ticker/"
    guard let url = URL(string: jsonURL) else {
        print("Invalid URL provided")
        return
    }
    
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        // Handle network errors first
        if let error = error {
            print("Network error: \(error.localizedDescription)")
            return
        }
        
        guard let data = data else {
            print("No data received from the API")
            return
        }
        
        do {
            // Decode JSON directly into your coins array
            self.coins = try JSONDecoder().decode([Coin].self, from: data)
            
            // Refresh the table on the main thread—only once after all data is loaded
            DispatchQueue.main.async {
                self.coinTableView.reloadData()
            }
        } catch {
            print("JSON decoding error: \(error)")
        }
    }.resume()
}

Key Improvements

  • Single Source of Truth: Using the coins array directly ensures your cell data is always consistent.
  • Safe Value Conversion: Optional binding (if let) prevents crashes if the percentage string isn't a valid number.
  • Better Performance: Refreshing the table once instead of 200 times reduces unnecessary UI updates.

内容的提问来源于stack exchange,提问作者cs4alhaider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:46:36