簡體   English   中英

如何將CAGradientLayer添加到UIButton

[英]How to add CAGradientLayer to 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.playButtonself.view那么它增添了一道靚麗的紅色,綠色漸變層到UIView

值得注意的是,我將自定義按鈕定義為IBOutlet如下所示:

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

任何幫助是極大的贊賞。

更新和修復

當改變按鈕采用可擴展性的圖像,而不是一個坡度,我忘了重新注釋掉的代碼梯度(嘗試后rokjarc和更改按鈕的時候的想法) imageView.contentUIViewContentModeScaleToFill顯示梯度...

self.playButton.imageView.contentMode = UIViewContentModeScaleToFill;

所以,謝謝rokjarc,我想:D

簡單地改變

self.playButton.backgroundColor = [UIColor blackColor];

self.playButton.backgroundColor = [UIColor clearColor];

剛剛測試過,它有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM