从@Andrey Gordeev 建议的解决方法开始,我将其扩展为包括在取消选择单元格后删除样式层。
由于其他原因,我仍然需要使用我的自定义单元格,但我已将其显示为下面的标准单元格,因此任何人都可以使用它
如果你必须打电话应用你自己的风格
[myTable selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
选择单元格时添加渐变层
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
CAGradientLayer *gradient = [CAGradientLayer layer];
[gradient setFrame:[cell.contentView bounds]];
[gradient setColors:[NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:0.70 alpha:1.0] CGColor], (id)[[UIColor colorWithWhite:0.50 alpha:1.0] CGColor], nil]];
[[cell.contentView layer] insertSublayer:gradient atIndex:0];
// The next line makes a reference to the gradient layer for selection and removal later on
[[cell.contentView layer] setValue:gradient forKey:@"GradientLayer"];
...
}
取消选择单元格时删除渐变层
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
// Get the layer using the reference to it
CALayer *gradientLayer = [[cell.contentView layer] valueForKey:@"GradientLayer"];
[gradientLayer removeFromSuperlayer];
[[cell.contentView layer] setValue:nil forKey:@"GradientLayer"];
...
}