2014-02-06 22 views
0

我在UICollectionView上用下面的代碼繪製了漸變背景圖層。我無法在iPad上繪製完全漸變背景

CAGradientLayer* collectionRadient = [CAGradientLayer layer]; 
collectionRadient.bounds = self.collectionView.bounds; 
collectionRadient.anchorPoint = CGPointZero; 
collectionRadient.colors = [NSArray arrayWithObjects:(id)[startColor CGColor],(id)[endColor CGColor], nil]; 
UIView* vv = [[UIView alloc] init]; 
self.collectionView.backgroundView = vv; 
[self.collectionView.backgroundView.layer insertSublayer:collectionRadient atIndex:0]; 

它適用於iPhone模擬器。但不是iPad。 下面是圖片。背景層只佔用UICollectionView的一部分。

enter image description here

回答

1

我建議創建一個名爲GradientView的UIView的子類或類似的東西,你會爲你的背景視圖中使用。

在您的實現GradientView的你只需要重載以下類方法:

+ (Class)layerClass 
{ 
    return [CAGradientLayer class]; 
} 

然後,更改上面的代碼爲以下:

UIView* backgroundView = [[GradientView alloc] initWithFrame:self.collectionView.bounds]; 
backgroundView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); 
self.collectionView.backgroundView = backgroundView; 
CAGradientLayer* collectionGradient = (CAGradientLayer *)backgroundView.layer; 
collectionGradient.anchorPoint = CGPointZero; 
collectionGradient.colors = [NSArray arrayWithObjects:(id)[startColor CGColor],(id) [endColor CGColor], nil]; 

我希望您的自定義GradientView的圖層會自動調整大小。如果不是,則可能需要在自定義GradientView中實現layoutSubviews方法來調整漸變圖層的大小。

+0

另一個注意事項:在使用CAGradientLayer時,我已經看到過去的一些條帶問題。如果這不起作用,您可以考慮在您的GradientView子類中實現drawRect以使用Core Graphics繪製漸變。 – slpaulson

+0

感謝您的回覆。它工作得很好。 還有一件事,我收到警告消息,「不兼容的指針類型初始化'CAGradientLayer * __ strong'與'CALayer *'類型的表達式。是否應該明確地向CAGradient投放? – nao0811ta

+0

是的,你應該可以將圖層投射到CAGradientLayer。否則,您可以添加CAGradientLayer類型的只讀屬性,該屬性只返回視圖圖層的強制轉換,以便該類的用戶不需要假定該圖層是漸變圖層。 – slpaulson