我在一个列表中使用了一个dequeueReusableCell
,单元格中有4个UILabel。下面有截图。
凡是有“-”字头的标签,都是红色的,但翻了几页,数字就乱七八糟了。想知道是否有办法避免这种情况?
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeTableCell", for: indexPath)
let currentRecipe = recipes?[indexPath.row]
let colorRed = UIColor(red: 0xFE/255, green: 0x38/255, blue: 0x24/255, alpha: 1) //FE3824
(cell.viewWithTag(100) as! UIImageView).image = UIImage(named: currentRecipe?.pic ?? "")
(cell.viewWithTag(200) as! UILabel).text = currentRecipe?.name
let hungryLabel = cell.viewWithTag(301) as! UILabel
hungryLabel.text = currentRecipe?.hungry_value
if (currentRecipe?.hungry_value!.hasPrefix("-"))! {
hungryLabel.textColor = colorRed
}
let healthLabel = (cell.viewWithTag(302) as! UILabel)
healthLabel.text = currentRecipe?.health_value
if (currentRecipe?.health_value!.hasPrefix("-"))! {
healthLabel.textColor = colorRed
}
let sanityLabel = (cell.viewWithTag(303) as! UILabel)
sanityLabel.text = currentRecipe?.sanity_value
if (currentRecipe?.sanity_value!.hasPrefix("-"))! {
sanityLabel.textColor = colorRed
}
(cell.viewWithTag(304) as! UILabel).text = currentRecipe?.duration
return cell
}
谢谢你们。
I add a Black Color to 'else', it works, thank you
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeTableCell", for: indexPath)
let currentRecipe = recipes?[indexPath.row]
let colorRed = UIColor(red: 0xFE/255, green: 0x38/255, blue: 0x24/255, alpha: 1) //FE3824
let colorBlack = UIColor(red: 74/255, green: 74/255, blue: 74/255, alpha: 1) //747474
(cell.viewWithTag(100) as! UIImageView).image = UIImage(named: currentRecipe?.pic ?? "")
(cell.viewWithTag(200) as! UILabel).text = currentRecipe?.name
let hungryLabel = cell.viewWithTag(301) as! UILabel
hungryLabel.text = currentRecipe?.hungry_value
if (currentRecipe?.hungry_value!.hasPrefix("-"))! {
hungryLabel.textColor = colorRed
} else {
hungryLabel.textColor = colorBlack
}
let healthLabel = (cell.viewWithTag(302) as! UILabel)
healthLabel.text = currentRecipe?.health_value
if (currentRecipe?.health_value!.hasPrefix("-"))! {
healthLabel.textColor = colorRed
} else {
healthLabel.textColor = colorBlack
}
let sanityLabel = (cell.viewWithTag(303) as! UILabel)
sanityLabel.text = currentRecipe?.sanity_value
if (currentRecipe?.sanity_value!.hasPrefix("-"))! {
sanityLabel.textColor = colorRed
} else {
sanityLabel.textColor = colorBlack
}
(cell.viewWithTag(304) as! UILabel).text = currentRecipe?.duration
return cell
}
最佳答案
在您的 cellForRowAt 方法中,您需要检查值是否为正,颜色为黑色,如果为负,则颜色为红色。例如
label.color = black
if negativeValue {
lagel.color = red
}
关于ios - 如何在不弄乱内容的情况下标记 dequeueReusableCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44962181/