Swift 根据数据快速更改tableviewcell边框颜色

Swift 根据数据快速更改tableviewcell边框颜色,swift,uitableview,swift3,custom-cell,Swift,Uitableview,Swift3,Custom Cell,我已经编写了一个代码,用于根据inStock或outStock更改单元格边框颜色,如果是inStock,则为红色边框,否则为绿色边框,但我认为它不适用于我,我将其放在willDisplayCell中,这是我的代码: func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPa

我已经编写了一个代码,用于根据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

    }



}

您正在为每个单元多次添加whiteRoundedView,因为单元实例被重用

您应该只创建一次(在创建UITableViewCell时),然后在willDisplayCell函数中操作它的颜色


我建议您创建自定义UITableViewCell,但您也可以通过使用view“tag”属性并检查它是否已经存在来避免该问题。

尝试将代码移动到
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

谢谢,效果很好,但问题是边框粘在桌子边上了,我需要更小的边