【发布时间】:2014-02-16 00:32:50
【问题描述】:
我正在尝试在 UITableViewCell 的底部添加一个 CALayer 以获得一点“阴影”效果。问题是当表格向上滚动并离开屏幕时,图层被删除,因此当您向下滚动时它不可见。如果您将单元格向下滚动到屏幕之外,然后将它们备份起来,它们看起来很好。
I have a gif here showing what's happening.
这就是我的做法:
- (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;
}
【问题讨论】:
标签: ios objective-c uitableview calayer