我一直在寻找一种简单的方法来为UITextView的文本添加阴影,就像你可以在UILabel中做的那样。我发现this question哪里有一个应该这样做的答案,但是,为什么这应该是这样的,这没有意义。如何将文字阴影添加到UITextView?
问题:向UITextView本身的图层添加阴影不应该影响里面的文本,而应该影响整个对象,对吗?
在我的情况下,即使向textview的图层添加阴影也没有任何效果(甚至在添加QuartzCore标题之后)。
我一直在寻找一种简单的方法来为UITextView的文本添加阴影,就像你可以在UILabel中做的那样。我发现this question哪里有一个应该这样做的答案,但是,为什么这应该是这样的,这没有意义。如何将文字阴影添加到UITextView?
问题:向UITextView本身的图层添加阴影不应该影响里面的文本,而应该影响整个对象,对吗?
在我的情况下,即使向textview的图层添加阴影也没有任何效果(甚至在添加QuartzCore标题之后)。
@阿达利的回答会的工作,但它的错。您不应该将阴影添加到UITextView
本身,以实现内部的可见视图。如您所见,通过将阴影应用于UITextView
,光标也将具有阴影。
应该使用的方法是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;
但textView.attributedText
适用于iOS6。如果您必须支持较低版本,则可以使用以下方法。
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;
我试过,发现,你应该设置的UITextView的的backgroundColor透明, 所以影子应该工作
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];
作品,感谢,感激 – johnbakers
哈哈,iOS6的是不是我就回答了这个问题:) – adali
是啊,它很难保持这些评论是最新发布的:P – cnotethegr8