TableView单元格视图阴影在Swift中无法正常显示

时间:2020-02-02 11:58:43

标签: swift uitableview uiview shadow

我已将view添加为tableview单元的背景,并且正在为view提供阴影。在这里,当我运行tableview时,阴影不会正确显示,一旦我上下滚动,阴影就会正确显示。

根据这个答案answer

代码:

  extension UIView {
  func dropShadow(scale: Bool = true) {
  layer.masksToBounds = false
  layer.shadowColor = UIColor.black.cgColor
  layer.shadowOpacity = 0.5
  layer.shadowOffset = CGSize(width: -1, height: 1)
  layer.shadowRadius = 1
  layer.shadowPath = UIBezierPath(rect: bounds).cgPath
  layer.shouldRasterize = true
  layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PlansTableViewCell

    cell.containerView.dropShadow()
    return cell
}

在滚动阴影出现之前,

enter image description here

滚动后如下图所示:

enter image description here

运行后(滚动之前),我还需要第二种图像输出,这里请提供代码帮助我。

1 个答案:

答案 0 :(得分:1)

问题在这里

layer.shadowPath = UIBezierPath(rect: bounds).cgPath

bounds当时不正确,请尝试 从

调用
override func layoutSubviews() {
   super.layoutSubviews()
   self.containerViewdropShadow()
}

cell.layoutIfNeeded()
cell.containerView.dropShadow()