I’ve got a UITextView, with scrollable text.
I’m trying to apply a gradient layer to it, so the bottom of the visible text is always slightly faded out.
Here’s my code:
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor], (id)[[UIColor yellowColor] CGColor], nil];
maskLayer.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],
[NSNumber numberWithFloat:0.2],
[NSNumber numberWithFloat:0.8],
[NSNumber numberWithFloat:1.0], nil];
maskLayer.bounds = clueTextView.bounds;
myUITextView.layer.mask = maskLayer;
Right now, this is causing the UITextViewLayer to be completely transparant – I see the background color of the UIView that the UITextViewLayer is as subview of. I can’t see any of the text contained within, although I can select and copy the text to paste in to the notes program.
Any ideas what I’m missing?
You have several problems.
The gradient layer’s
colorsproperty needs to have the same count as itslocationsproperty. You are providing 4 locations but only 2 colors.You are setting the gradient layer’s bounds based on
clueTextViewbut you are setting it as the mask ofmyUITextView.You are setting the
boundsof the gradient layer, but not itsposition. The defaultpositionis 0,0, meaning that the center of the gradient layer is at the upper-left corner ofmyUITextView. It is simpler to just set theframeof the gradient layer to theboundsof the text view.If you fix all of these problems, you might get the effect you’re looking for.
However, you may discover new problems.
If the user can scroll the text view, you will discover that the gradient moves with the text view, which is probably not what you want. The easiest way to fix this is to embed the text view inside a container
UIView, and set the mask on the container view.If the text view can change size (perhaps due to device rotation), the mask will not automatically change size with it. You need to update the mask’s
frame, inlayoutSubviewsorviewDidLayoutSubviews.