UILabel text color transparency with layer shadows

2019-08-29 13:12发布

问题:

I have a UILabel to which I am attempting to apply a semi-transparent gradient as a color onto. For example, in my UILabel subclass I'm trying to set the gradient color this way:

self.textColor = [UIColor colorWithPatternImage:someTransparentGradient];

While messing around with this, however, I discovered that a UILabel doesn't seem to be able to draw with transparency when layer shadows are in place. I attempted to set the text color to clear:

self.textColor = [UIColor clearColor];

but the text ended up being white. Ideas?

You can replicate the problem yourself if you set the text color to clear, then apply layer shadows onto the text view.

回答1:

If you would have created the UILabel through nib and set the textColor in initWithFrame, you will not get desired result.

In the UILabel sub-class, write initWithCoder and set the color.

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Initialization code
        self.textColor = [UIColor clearColor];
    }
    return self;
}

Edit

See, this is the screen shot with default (gray) background.

And this is the screenshot with white background

Please download the sample application and try it.



回答2:

I don't normally accept my own answers, but in this case I must. This seems to be a bug. Whenever layer shadows are applied to a UILabel, text transparency is no longer supported. I will file a radar.