我想在每个单元格的底部添加一个简单的渐变。在 cellForItemAtIndexPath:
我有代码:
CAGradientLayer *bottomFade = [CAGradientLayer layer];
bottomFade.name = @"Gradient";
bottomFade.frame = CGRectMake(0, cell.background.frame.size.height*0.8, cell.background.frame.size.width, cell.background.frame.size.height*0.2);
bottomFade.endPoint = CGPointMake(0.5, 1.0);
bottomFade.startPoint = CGPointMake(0.5, 0.0);
bottomFade.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:0.0 alpha:0.0f] CGColor], (id)[[UIColor colorWithWhite:0.0 alpha:0.2f] CGColor], nil];
[cell.background.layer addSublayer:bottomFade];
问题是当cell滚动的时候,sublayer会一遍又一遍的添加,这显然不是我们想要的效果。
当涉及到 UITableView
时,我知道如何处理可重用性问题,但是当涉及到 UICollectionView
时,我应该怎么做?
我试图设置一个自定义单元格属性 isConfigured
,但是当我在 cellForItemAtIndexPath:
中检查它时,结果是只生成了两个单元格,然后它们被重复(老实说,我完全不知道为什么)。
您有什么建议来处理这样的问题?也许在单元格的子类中添加一些自定义代码会更好?
最佳答案
将只需要一次的代码放在'awakeFromNib'中,这样它就不会在其生命周期中被调用两次或三次
看起来像这样:
- (void)awakeFromNib {
[super awakeFromNib];
CAGradientLayer *bottomFade = [CAGradientLayer layer];
bottomFade.name = @"Gradient";
bottomFade.frame = CGRectMake(0, self.background.frame.size.height*0.8, self.background.frame.size.width, self.background.frame.size.height*0.2);
bottomFade.endPoint = CGPointMake(0.5, 1.0);
bottomFade.startPoint = CGPointMake(0.5, 0.0);
bottomFade.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:0.0 alpha:0.0f] CGColor], (id)[[UIColor colorWithWhite:0.0 alpha:0.2f] CGColor], nil];
[self.background.layer addSublayer:bottomFade];
}
关于ios - 将 subview 添加到 UICollectionViewCell 一次(单元格可用性问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32048191/