tableviewcell 中带有 alpha 的渐变随着每次滚动而变暗
Gradient with alpha in tableviewcell gets darker with each scroll
我正在尝试在我的 tableviewcell 中设置透明渐变颜色。在第一次加载时一切正常,但每次滚动时,颜色都会再次加载,并且每次滚动时渐变似乎越来越暗,并且每次滚动时 tableview 似乎更滞后。这是我实现渐变颜色的代码:-
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
}
1) 将子视图添加到您的 Cell 中,并将其连接到您的视图控制器:
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
}
我正在尝试在我的 tableviewcell 中设置透明渐变颜色。在第一次加载时一切正常,但每次滚动时,颜色都会再次加载,并且每次滚动时渐变似乎越来越暗,并且每次滚动时 tableview 似乎更滞后。这是我实现渐变颜色的代码:-
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
}
1) 将子视图添加到您的 Cell 中,并将其连接到您的视图控制器:
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
}