我想在每个单元格的底部添加一个简单的渐变。在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];
问题是当滚动单元格时,会一遍又一遍地添加子图层,这显然不是理想的效果。
我知道在UITableView
方面如何处理可重用性问题,但在使用UICollectionView
时应该怎么做?
我尝试设置自定义单元格属性isConfigured
,但当我在cellForItemAtIndexPath:
中检查时,结果是只生成了两个单元格,然后它们重复(说实话,我绝对有不知道为什么)。
你有什么建议来处理这样的问题?也许最好在单元格的子类中添加一些自定义代码?
答案 0 :(得分:2)
将您的代码只需要一次内部唤醒' 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];
}
答案 1 :(得分:0)
我已经解决了这个问题;)。
在单元格的子类中:
-(void)layoutSubviews {
if (!self.isConfigured) {
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];
self.isConfigured = YES;
}
}
诀窍就好了!但是,我仍然非常好奇cellForItemAtIndexPath:
是否可以轻松解决问题。
答案 2 :(得分:0)
每次UICollectionView实例创建或重用UICollectionViewCell时,都会调用cellForItemAtIndexPath:
方法,这就是问题所在。
我建议您不要使用像isConfigured
这样的属性,单元格应保留BOOL变量,并且每次调用layoutSubviews
时都会检查属性,这会浪费内存和性能。
正如nferocious76所说,awakeFromNib:
方法,在其生命周期中仅被调用一次,是此案例的最佳解决方案。
顺便说一句,由于我无法发表评论,您应该在[super layoutSubviews]
方法的开头致电layoutSubviews
。