如何将文字阴影应用于UITextView?

其实我爱UILabel 。 他们很甜蜜 现在我不得不去UITextView因为UILabel没有将文本垂直alignment。 该死的。 我真正需要的是一个文字阴影。 UILabel有它。 UITextView似乎没有它。 但我猜这家伙只是使用相同的基础UIKit NSString补充? 也许有人已经有这个问题的解决scheme? 我会覆写什么?

 text.layer.shadowColor = [[UIColor whiteColor] CGColor]; text.layer.shadowOffset = CGSizeMake(1.0f, 1.0f); text.layer.shadowOpacity = 1.0f; text.layer.shadowRadius = 1.0f; 

别忘了加上top:

 #import <QuartzCore/QuartzCore.h> 

答案与

text.layer.shadowColor

为整个textView添加阴影,也许它工作,但它不仅添加到文本的阴影。

正确的答案是:

 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 = 1.0f; 

Swift 3


 let textView = UITextView(frame: view.frame) textView.font = UIFont(name: "Helvetica", size: 64.0) textView.textColor = .red textView.text = "Hello World" textView.layer.shadowColor = UIColor.black.cgColor textView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0) textView.layer.shadowOpacity = 1.0 textView.layer.shadowRadius = 2.0 textView.layer.backgroundColor = UIColor.clear.cgColor 

Swift 2.3


 let textView = UITextView(frame: view.frame) textView.font = UIFont(name: "Helvetica", size: 64.0) textView.textColor = UIColor.redColor() textView.text = "Hello World" textView.layer.shadowColor = UIColor.blackColor().CGColor textView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0) textView.layer.shadowOpacity = 1.0 textView.layer.shadowRadius = 2.0 textView.layer.backgroundColor = UIColor.clearColor().CGColor 

在iOS 6+使用归因文本

 NSShadow * shadow = [[NSShadow alloc] init]; shadow.shadowColor = [UIColor blackColor]; shadow.shadowOffset = CGSizeMake(2, 2); NSDictionary * textAttributes = @{ NSForegroundColorAttributeName : [UIColor blueColor], NSShadowAttributeName : shadow, NSFontAttributeName : [UIFont boldSystemFontOfSize:20] }; textView.attributedText = [[NSAttributedString alloc] initWithString:@"Hello" attributes:textAttributes]; 

你好例子

在这里输入图像说明

这个Swift示例使用向文本添加阴影的属性string方法。 有关Swift中的归因string的更多信息,请参阅此答案 。 这种方法(与使用图层方法相反)使您可以灵活地在一定范围的文本上设置阴影(如果需要)。

 // Create a string let myString = "Shadow" // Create a shadow let myShadow = NSShadow() myShadow.shadowBlurRadius = 3 myShadow.shadowOffset = CGSize(width: 3, height: 3) myShadow.shadowColor = UIColor.gray // Create an attribute from the shadow let myAttribute = [ NSShadowAttributeName: myShadow ] // Add the attribute to the string let myAttrString = NSAttributedString(string: myString, attributes: myAttribute) // set the attributed text on a label myLabel.attributedText = myAttrString // can also use with UITextView 

这取决于你使用的iOS版本。 从iOS 6开始,支持单个阴影,将其设置为NSAttributedString上的一个属性,然后在标签上设置该属性。