在UITableViewCell中绘制阴影会导致视觉错误

时间:2018-07-25 06:55:02

标签: ios swift uitableview

我是新手。我想在UITableViewCell中的视图后面绘制阴影,但是当我添加以下代码时:

func doTheWork(statutOfCard : statut){
    switch statutOfCard {
    case .selectPicture:
        cardViewHeightCon.constant = 300
        if ShadowLayerCard == nil{
            self.addCardShadow()
        }
    case .modifyPicture:
        cardViewHeightCon.constant = 400
        if ShadowLayerCard == nil{
            self.addCardShadow()
        }
    default:
        cardViewHeightCon.constant = 300
        if ShadowLayerCard == nil{
            self.addCardShadow()
        }
    }
}

func addCardShadow(){
    let shadowLayer = CAShapeLayer()
    ShadowLayerCard = shadowLayer
    shadowLayer.path = UIBezierPath(roundedRect: CGRect(0, 0, widthOfDevice! - (widthMarginConstraint*2), cardViewHeightCon.constant), cornerRadius: 10).cgPath
    shadowLayer.fillColor = UIColor(rgb: 0x00ff33).cgColor
    shadowLayer.shadowPath = shadowLayer.path
    shadowLayer.shadowColor = UIColor.black.cgColor
    shadowLayer.shadowRadius = 5
    shadowLayer.shadowOpacity = 0.2
    shadowLayer.shadowOffset = CGSize(width: 0, height: 0)
    cardView.layer.insertSublayer(shadowLayer, at: 0)
}

阴影出现在UITableViewCell中,但是当我向下滚动时,会产生如下视觉错误:

我认为阴影是在cardView的高度更新之前绘制的,但是如何解决此问题?而且,如果我需要以编程方式添加图片等其他组件,是否可以在doTheWork函数中编写呢?还是会再次产生错误?

1 个答案:

答案 0 :(得分:1)

将阴影添加到cardView.layer,并在创建单元格时执行一次。您可能需要另一个视图来保留带有圆角的图像,因为您需要将clip设置为true限制角。

func addCardShadow(){
    let shadowLayer = cardView.layer
    shadowLayer.shadowColor = UIColor.black.cgColor
    shadowLayer.shadowRadius = 5
    shadowLayer.shadowOpacity = 0.2
    shadowLayer.shadowOffset = CGSize(width: 2, height: 2)
}