【发布时间】:2017-07-07 03:43:24
【问题描述】:
我在列表中使用了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
}
谢谢你们。
我在“else”中添加了黑色,它可以工作,谢谢
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
}
【问题讨论】:
-
Edit 你的问题与你的
cellForRowAt方法。 -
向我们展示您根据前缀“-”管理标签颜色的代码。
-
细胞被重复使用。在
cellForRow添加一个else子句,如果值为not 负数,则显式将颜色设置为黑色。 -
@vadian 谢谢它有帮助
-
PS:
viewWithTag非常老套。在 IB 中设计一个 custom 单元并使用 outlet。对于灰度颜色,有一个方便的初始化程序let colorBlack = UIColor(white: 74/255, alpha: 1)。
标签: ios swift uitableview tableview