2012-12-28 91 views
3

我想修改按鍵的外觀和花了很長時間試圖弄清楚爲什麼我不能一個梯度適用於它像下面這個簡單的代碼:如何CAGradientLayer添加到UIButton的

[self.playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
self.playButton.backgroundColor = [UIColor blackColor]; 

CAGradientLayer *gradient = [[CAGradientLayer alloc] init]; 
gradient.frame = self.playButton.bounds; 
gradient.position = CGPointMake(self.playButton.bounds.size.width/2, self.playButton.bounds.size.height/2); 
gradient.colors = [NSArray arrayWithObjects: 
        (id)[UIColor greenColor].CGColor, 
        (id)[UIColor redColor].CGColor, 
        nil]; 
gradient.locations = [NSArray arrayWithObjects: 
         [NSNumber numberWithFloat:0.0f], 
         [NSNumber numberWithFloat:1.0f], 
         nil]; 

[self.playButton.layer addSublayer:gradient]; 

它執行,但沒有任何反應。我知道代碼應該可以工作,因爲許多其他人使用它,當將self.playButton更改爲self.view時,它會在UIView上添加一個美麗的紅綠色漸變圖層。

這可能是值得注意的是,我的自定義按鈕被定義爲IBOutlet這樣的:

@property (weak, nonatomic) IBOutlet UIButton *playButton; 

任何幫助不勝感激。

UPDATE & FIX

當改變按鈕,使用一個可擴展的圖像,而不是漸變的,我忘了重新註釋時的梯度代碼和改變時(試圖rokjarc的想法後)按鈕的imageView.contentUIViewContentModeScaleToFill顯示的梯度......

self.playButton.imageView.contentMode = UIViewContentModeScaleToFill; 

所以感謝rokjarc我想:d

回答

1

簡單地改變

self.playButton.backgroundColor = [UIColor blackColor]; 

self.playButton.backgroundColor = [UIColor clearColor]; 

只是測試和它的作品。

+0

也嘗試過,但那也行不通。我想申請一個漸變,就像下面的鏈接中所解釋的那樣,但是因爲既沒有光滑的漸變,也沒有我的紅綠漸變顯示,我真的迷失了。 http://stackoverflow.com/questions/6936917/how-to-create-a-uibutton-with-a-black-gradient-for-iphone –

+1

好像'imageView.content'模式沒有正確設置。將其更改爲'UIViewContentModeScaleToFill',現在它工作:o –

+0

它不起作用 – Tom