我想在我的UITableViewCell底部添加一个CALayer,以获得一些“阴影”效果。问题是当表格向上滚动并向屏幕上方滚动时,该图层会被移除,所以当您向下滚动时它不可见。如果将单元格向下滚动到屏幕外,然后再向上滚动,它们就会显示正常。
这是我的做法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:@"Row %d", (int)indexPath.row];
CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(0.0f, cell.frame.size.height, cell.frame.size.width, 1.0f);
bottomBorder.backgroundColor = [UIColor colorWithWhite:0.9f alpha:1.0f].CGColor;
[cell.layer addSublayer:bottomBorder];
cell.clipsToBounds = NO;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
我也尝试使用每个单元格的唯一cellIdentifier,希望它们不会被重用,因此图层永远不会像这样被移除:
//Same code as before just this changed
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"%ld_%ld", (long)indexPath.row, (long)indexPath.section]];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"%ld_%ld", (long)indexPath.row, (long)indexPath.section]];
}
//Same code continued...
当单元格被重用时,添加到其中的CALayer会被移除。为了让该层在单元格滚动离开和重新进入屏幕时保持存在,我需要做什么?
编辑:
我也尝试了这个方法,但它也不起作用:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(0.0f, cell.frame.size.height, cell.frame.size.width, 1.0f);
bottomBorder.backgroundColor = [UIColor colorWithWhite:0.9f alpha:1.0f].CGColor;
[cell.layer addSublayer:bottomBorder];
cell.clipsToBounds = NO;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text = [NSString stringWithFormat:@"Row %d", (int)indexPath.row];
return cell;
}