Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add text shadows to a UITextView?

I've been searching around to find an easy way to add shadows to the text of a UITextView, like you can do in a UILabel. I found this question where there was an answer that supposedly does this, however, it makes no sense why this should be the case.

Question: Adding shadows to the layer of the UITextView itself should not affect the text inside, rather it should shadow the entire object, right?

In my case, even adding the shadow to the layer of the textview is not having any effect (even after adding the QuartzCore headers).

like image 285
johnbakers Avatar asked Nov 20 '25 17:11

johnbakers


2 Answers

i tried, and found that , you should set the UITextView's backgroundcolor to transparent, so the shadow should work

    UITextView *text = [[[UITextView alloc] initWithFrame:CGRectMake(0, 0, 150, 100)] autorelease];
    text.layer.shadowColor = [[UIColor whiteColor] CGColor];
    text.layer.shadowOffset = CGSizeMake(2.0f, 2.0f);
    text.layer.shadowOpacity = 1.0f;
    text.layer.shadowRadius = 1.0f;
    text.textColor  = [UIColor blackColor];

            //here is important!!!!
    text.backgroundColor = [UIColor clearColor];

    text.text = @"test\nok!";
    text.font = [UIFont systemFontOfSize:50];

    [self.view addSubview:text];

here is the effect

like image 129
adali Avatar answered Nov 23 '25 07:11

adali


@adali's answer will work, but its wrong. You shouldn't add the shadow to the UITextView itself in order to effect the visible views inside. As you can see, by applying the shadow to the UITextView the cursor will also have the shadow.

The approach that should be used is with NSAttributedString.

NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:textView.text];
NSRange range = NSMakeRange(0, [attString length]);

[attString addAttribute:NSFontAttributeName value:textView.font range:range];
[attString addAttribute:NSForegroundColorAttributeName value:textView.textColor range:range];

NSShadow* shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor whiteColor];
shadow.shadowOffset = CGSizeMake(0.0f, 1.0f);
[attString addAttribute:NSShadowAttributeName value:shadow range:range];

textView.attributedText = attString;

However textView.attributedText is for iOS6. If you must support lower versions, you could use the following approach.

CALayer *textLayer = (CALayer *)[textView.layer.sublayers objectAtIndex:0];
textLayer.shadowColor = [UIColor whiteColor].CGColor;
textLayer.shadowOffset = CGSizeMake(0.0f, 1.0f);
textLayer.shadowOpacity = 1.0f;
textLayer.shadowRadius = 0.0f;
like image 43
cnotethegr8 Avatar answered Nov 23 '25 08:11

cnotethegr8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!