I am trying to set transparent gradient color in my tableviewcell. Everything works fine in the first load but with each scroll, the color are loaded again and the gradient seems to be darker and darker with each scroll and with each scroll the tableview seems to be laggier. Here's my code for implementing gradient color :-
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.contentView.layer.insertSublayer(gradient(cell.bounds), atIndex: 1)
}
func gradient(frame:CGRect) -> CAGradientLayer {
let layer = CAGradientLayer()
layer.frame = frame
layer.startPoint = CGPointMake(0,0.68)
layer.endPoint = CGPointMake(0,0.75)
layer.colors = [UIColor.clearColor().CGColor,UIColor.blackColor().colorWithAlphaComponent(0.2).CGColor]
return layer
}
答案 0 :(得分:2)
1)向您的Cell添加子视图,并将其连接到View控制器:
class MyCell : UITableViewCell {
@IBOutlet weak var bgView: UIView!
}
2)从 willDisplayCell 方法移除您的行,将其移至 cellForRowAt ()方法,更新如下:
override func tableView(tableView: UITableView, cellForRowAtIndexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
if(cell.bgView.layer.sublayers == nil) {
cell.bgView.layer.insertSublayer(gradient(frame: cell.bounds), at: 1)
}
return cell
}