2011-08-04 67 views

回答

39

总是令人敬畏的Ray Wenderlich做了一个关于改变UITableViewCells的教程,并且包含一个渐变。

http://www.raywenderlich.com/2033/core-graphics-101-lines-rectangles-and-gradients

如果你想快速的方式,这里的一些代码:

//include #import <QuartzCore/QuartzCore.h> in the header… 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

if (cell == nil) { 
     cell = [[DayCalendarCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     CAGradientLayer *gradient = [CAGradientLayer layer]; 
     gradient.frame = cell.bounds; 
     gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor]CGColor], (id)[[UIColor redColor]CGColor], nil]; 
     [cell.layer addSublayer:gradient]; 
    }   
    return cell; 
} 

你可以改变颜色,但这样会给你一个好主意......

祝你好运!

+0

这段代码有错误。当颜色被添加到NSArray时,需要将颜色转换为类型ID。见下文。 [NSArray arrayWithObjects:(id)[UIColor whiteColor] .CGColor,(id)[UIColor redColor] .CGColor,nil]; 除此之外,它的效果很好。谢谢你的伟大答案! – jmurphy

+0

你是对的。对于那个很抱歉! –

+2

如果您在UITableViewCell的其他图层/子视图上需要使用此方法,请注意,因为您的渐变可能会在其上绘制它们。 –

1

Peronally我会在Photoshop或gimp中创建一个渐变图像,然后将其用作背景。只要细胞具有可预测的大小,应该可以正常工作。

+0

这就是我所做的。 –

+4

如果您需要可变高度的渐变,则这不起作用。另外,如果可以通过编程实现相同的效果,那么这样做可能是明智的,因为它使得.ipa更小。只是我的2美分 – ArtSabintsev

2

创建X高度的1px图像。

在cellForRowAtIndexPath方法的单元格中添加UIView对象。

UWiew setbackgroundcolor方法中的uWolor的colorWithPatterImage方法。

+0

这是一个很好的方法。使用'[UIColor colorWithPatternImage:]' –

2

关注雅各的答案,并设置一个UIButton或任何View使用的背景颜色:中

[button.layer insertSublayer:gradient atIndex:0]; 

代替:

[button.layer addSublayer:gradient]; 
+0

我也必须将背景颜色设置为透明。 – testing