Ios 单元格在滚动时应用额外的阴影
我正在尝试将阴影添加到自定义的Ios 单元格在滚动时应用额外的阴影,ios,swift,uitableview,tableviewcell,Ios,Swift,Uitableview,Tableviewcell,我正在尝试将阴影添加到自定义的UITableViewCell,一切正常,但当我滚动tableview时,单元格的阴影将不断应用,并使阴影变厚。这是我的密码: func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell
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
}
UITableViewCell是一个可重用的视图。这意味着,由于滚动时会调用cellForRow,因此阴影将在某个点再次应用于视图 例如:视图A、B、C在屏幕上,当您向下滚动并隐藏视图A时,视图A将被重新使用,并且视图A的阴影将再次创建 对于您的情况,我将在you DriverCell中建议在init中添加阴影,如下所示:
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")
}
}
这样,当视图初始化时将绘制阴影,此后将不再绘制阴影谢谢!但是
awakeFromNib
不是正确的解决方案。