[英]Swift Change the tableviewcell border color according to data
我已根據inStock或outStock寫了一個代碼來改變單元邊框的顏色,如果它在inStock它將是紅色邊框,否則它將是綠色的,但我不適合我,我把它放在willDisplayCell中,這里是我的代碼:
func tableView(_ tableView: UITableView,
willDisplay cell: UITableViewCell,
forRowAt indexPath: IndexPath){
cell.backgroundColor = UIColor.clear
cell.contentView.backgroundColor = UIColor.clear
let whiteRoundedView : UIView = UIView(frame: CGRect(x:10,y: 5,width: self.view.frame.size.width - 20,height: 214))
whiteRoundedView.layer.masksToBounds = false
whiteRoundedView.layer.cornerRadius = 5.0
whiteRoundedView.layer.shadowOffset = CGSize(width: -1,height: 1)
whiteRoundedView.layer.borderWidth = 2
cell.contentView.addSubview(whiteRoundedView)
cell.contentView.sendSubview(toBack: whiteRoundedView)
if stock[indexPath.row] == "inStock" {
whiteRoundedView.layer.borderColor = UIColor.red.cgColor
}
else {
whiteRoundedView.layer.borderColor = UIColor.green.cgColor
}
}
嘗試將代碼移動到像這樣的cellForRowAt
方法
cell.layer.masksToBounds = true
cell.layer.cornerRadius = 5
cell.layer.borderWidth = 2
cell.layer.shadowOffset = CGSize(width: -1, height: 1)
let borderColor: UIColor = (stock[indexPath.row] == "inStock") ? .red : .green
cell.layer.borderColor = borderColor.cgColor
您正在為每個單元格多次添加whiteRoundedView - 因為重用了單元格實例。
你應該只創建一次(創建UITableViewCell時) - 然后在willDisplayCell函數中操作它的顏色。
我建議創建自定義UITableViewCell,但您也可以通過使用視圖“tag”屬性並檢查它是否已存在來避免該問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.