我正在尝试添加阴影并添加到自定义UITableViewCell
,一切正常但是当我滚动tableview时,单元格的阴影将被应用于其上并使阴影更厚。这是我的代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DriverCell
//Create space between cells
cell.contentView.backgroundColor = UIColor(red:0.88, green:0.94, blue:0.99, alpha:1.00)
let whiteRoundedView : UIView = UIView(frame: CGRect(x:8, y:10, width: self.view.frame.size.width - 15 , height:150))
whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 1.0])
whiteRoundedView.layer.masksToBounds = false
whiteRoundedView.layer.cornerRadius = 9.0
whiteRoundedView.layer.shadowOffset = CGSize(width: 0, height: 0)
whiteRoundedView.layer.shadowRadius = 1.5
whiteRoundedView.layer.shadowOpacity = 0.2
whiteRoundedView.clipsToBounds = false
cell.contentView.addSubview(whiteRoundedView)
cell.contentView.sendSubview(toBack: whiteRoundedView)
return cell
}
答案 0 :(得分:1)
UITableViewCell是一个可重用的视图。这意味着因为滚动时会调用cellForRow,所以会在某个点再次应用阴影。
例如:视图A,B,C在屏幕上,当您向下滚动并且视图A被隐藏时,视图A将被重用,并且将再次为视图A创建阴影。
对于你的情况,我建议你在DriverCell中添加阴影,如下所示:
class DriverCell: UITableViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = UIColor(red:0.88, green:0.94, blue:0.99, alpha:1.00)
let whiteRoundedView : UIView = UIView(frame: CGRect(x:8, y:10, width: frame.size.width - 15 , height:150))
whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 1.0])
whiteRoundedView.layer.masksToBounds = false
whiteRoundedView.layer.cornerRadius = 9.0
whiteRoundedView.layer.shadowOffset = CGSize(width: 0, height: 0)
whiteRoundedView.layer.shadowRadius = 1.5
whiteRoundedView.layer.shadowOpacity = 0.2
whiteRoundedView.clipsToBounds = false
contentView.addSubview(whiteRoundedView)
contentView.sendSubview(toBack: whiteRoundedView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这样,在视图初始化时将绘制阴影,在
之后不再绘制阴影