Adding a CGGradient as sublayer to UILabel hides the text of label

前端 未结 5 1122
青春惊慌失措
青春惊慌失措 2020-12-03 17:17

I want to add the gradient as a background to label. I used the following code to acheive that. but the problem is that though the gradient color appears on the label, but t

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 17:49

    Inserting a sublayer to a UILabel hides the text, so the best way to get what you want is to add the label and gradient layer to a UIView.

    UIView *gradientLabelView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = gradientLabelView.bounds;
    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor],(id)[[UIColor colorWithRed:255/255.0 green:239/255.0 blue:215/255.0 alpha:1.0] CGColor],nil];
    
    [gradientLabelView.layer addSublayer:gradient];
    
    lblPatientDetail.frame = gradientLabelView.bounds;
    lblPatientDetail.backgroundColor = [UIColor clearColor];
    [gradientLabelView addSubview:lblPatientDetail];
    
    [self addSubview:gradientLabelView];
    

提交回复
热议问题