2011-08-04 64 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