UITableViewCell具有自定义渐变背景,另一个渐变为高亮颜色 [英] UITableViewCell with custom gradient background, with another gradient as highlight color

查看:255
本文介绍了UITableViewCell具有自定义渐变背景,另一个渐变为高亮颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自定义布局的自定义UITableViewCell。我想要一个渐变背景,所以在我的UITableViewDelegate cellForRowAtIndexPath:方法中,我创建了一个CAGradientLayer并使用insertSubLayer:atIndex:将其添加到单元格的图层中(使用索引0)。除了两件事之外,这很好用:

I have a custom UITableViewCell with a custom layout. I wanted a gradient background, so in my UITableViewDelegate cellForRowAtIndexPath: method, I create a CAGradientLayer and add it to the cell's layer with insertSubLayer:atIndex: (using index 0). This works just fine except for two things:

最重要的是,当突出显示行时,我无法弄清楚如何更改为不同的渐变颜色。我尝试了几件事,但是我对框架不够熟悉才能让它工作。在表格委托或单元格本身内放置代码的理想位置在哪里?

Most importantly, I can't figure out how to change to a different gradient color when the row is highlighted. I have tried a couple things, but I'm just not familiar enough with the framework to get it working. Where would be the ideal place to put that code, inside the table delegate or the cell itself?

此外,表格中每个单元格之间有1px的空白区域。我在主视图上有背景颜色,桌面上有背景颜色,单元格上有背景颜色。在UITableView中默认是否有某种填充或间隔?

Also, there's a 1px white space in between each cell in the table. I have a background color on the main view, a background color on the table, and a background color on the cell. Is there some kind of padding or spacer by default in a UITableView?

推荐答案

我知道这个线程已经老了,但是这里有一个解决方案对于问题的第一部分(向单元格的选定和未选定状态添加渐变):

I know this thread is old, but here's a solution for the first part of your question (adding a gradient to the selected and non-selected states of a cell):

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{    
    [cell setBackgroundColor:[UIColor clearColor]];

    CAGradientLayer *grad = [CAGradientLayer layer];
    grad.frame = cell.bounds;
    grad.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];

    [cell setBackgroundView:[[UIView alloc] init]];
    [cell.backgroundView.layer insertSublayer:grad atIndex:0];

    CAGradientLayer *selectedGrad = [CAGradientLayer layer];
    selectedGrad.frame = cell.bounds;
    selectedGrad.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];

    [cell setSelectedBackgroundView:[[UIView alloc] init]];
    [cell.selectedBackgroundView.layer insertSublayer:selectedGrad atIndex:0];
}

这篇关于UITableViewCell具有自定义渐变背景,另一个渐变为高亮颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆