Swift Change the tableviewcell border color according to data

我与影子孤独终老i 提交于 2020-08-04 03:39:29

问题


I have written a code for making the cell border color change according to inStock or outStock , if it is inStock it will be red border else it would be green, but I it is not working for me, I put it in willDisplayCell and here is my code :

 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

    }



}

回答1:


Try to move your code into cellForRowAt method like that

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



回答2:


You are adding your whiteRoundedView multiple time for each cell - as cell instances are reused.

You should only create this once (when creating UITableViewCell) - and then manipulate color of it after that in willDisplayCell function.

I would suggest creating custom UITableViewCell, but you can also avoid that problem by using view "tag" property and checking if it exists already.



来源:https://stackoverflow.com/questions/44663217/swift-change-the-tableviewcell-border-color-according-to-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!