Search code examples
objective-cuiviewcalayercagradientlayer

Objective C - CAGradientLayer covers the text in UILabel?


I am trying to add a gradient layet to my UILabel for some reasons the CAGradientLayer covers my text. Am I doing anything wrong

- (void)viewDidLoad {
   [super viewDidLoad];

   CAGradientLayer *gradient = [CAGradientLayer layer];
   gradient.frame = CGRectMake(0, 0, myLabel.frame.size.width, myLabel.frame.size.height);
   gradient.colors = myColors;
   [myLabel.layer insertSublayer:gradient atIndex:0];
}

Solution

  • The CAGradientLayer is covering the text of your label because the text is drawn by the content of the super layer that you explicitly covered by adding a sublayer.

    Your easiest solution is to use two views. A UIView subclass where you override +[UIView layerClass] and return a [CAGradientLayer]. Add a good init method to setup your gradient.

    Next pup add the UILabel as a subview of your custom gradient view.