2012-11-22 71 views
3

我使用QuartzCore为我的UITextView创建了一个阴影,并使用以下代码。使用QuartzCore为UITextView创建阴影

myTextView.layer.masksToBounds = NO; 
myTextView.layer.shadowColor = [UIColor blackColor].CGColor; 
myTextView.layer.shadowOpacity = 0.7f; 
myTextView.layer.shadowOffset = CGSizeMake(2.0f, 2.0f); 
myTextView.layer.shadowRadius = 8.0f; 
myTextView.layer.shouldRasterize = YES; 

它创建了一个shadowlooks good too.这是我对上面的代码输出。

enter image description here

但是当我尝试将文本添加到myTextView,我TextView的文本超出界限的,它看起来像myTextView以下之外。

enter image description here

当我添加阴影它的发生只。 textView里面的文字没有显示奇怪如果我不添加shadow.What我做错了?我怎么能克服这个?为什么会发生?

UPDATE:

@borrrden说 我发现它发生,因为设置maskToBounds = NO;如果我们设置YES那么我们就不能得到影子。原因这里是一个answer

+0

'masksToBounds'设置为'NO'。如果没有这个,视图将不会尝试剪辑其内容。 – borrrden

+0

如果我设置了** myTextView.layer.masksToBounds = YES; **那么它不会显示任何阴影。 –

+0

尝试将'textView.contentInset'设置为适当的值,以避免重叠。 – iDev

回答

6

由于UIView行为,没有“正确的”解决方案。当masksToBounds为NO时,任何延伸到图层边界之外的子图层都将可见。并且UITextField在UITextField图层之外滚动文本。

在UITextView背后添加清晰视图并在其上放置阴影。

+0

清晰视图是什么意思?如果我有另一个superview后面的textView? –

+0

我认为他的意思是添加一个单独的UIVIew作为textview背后的容器视图,并为其添加阴影效果。如果你在多个地方使用这个textview,可能你可以继承一个UIVIew并在自定义实现中添加textview作为子视图。 +1的建议。 – iDev

+0

@ACB但其实我试图给我的textview添加一个阴影。但是你正在给出替代解决方案。我已经知道在textView后面添加一个UIView,使其看起来像我想要的。无论如何,它的答案我的问题**我怎么能克服这个?**。但为什么我变得像我的输出?如果我想只为textView添加阴影?如果我有大量的textViews?然后,我需要无用地创建大量的UIViews,并为他们制作网点... –

2

只需添加您的TextView在另一个的UIView,并设置它的层来显示阴影(不要忘记设置它的背景颜色比透明色以外的东西 - 或者阴影不会被绘制)

myTextView = [UITextView alloc] initWithFrame:CGRectMake(100,100,200,200); 
UIView* shadowView = [UIView alloc] initWithFrame:myTextView.frame]; 
shadowView.backgroundColor = myTextView.backgroundColor; 
shadowView.layer.masksToBounds = NO; 
shadowView.layer.shadowColor = [UIColor blackColor].CGColor; 
shadowView.layer.shadowOpacity = 0.7f; 
shadowView.layer.shadowOffset = CGSizeMake(2.0f, 2.0f); 
shadowView.layer.shadowRadius = 8.0f; 
shadowView.layer.shouldRasterize = YES; 
[someView addSubview:shadowView]; 
[someView addSubView:myTextView]; 
+0

我需要为textView添加阴影而不是容器视图。 **你能帮我的输出,为什么它发生在我添加阴影到我的textView ?? ** –

+0

+1建议有一个替代方法.. –

1

除上一个答案,只需将原始uiTextView中的所有属性复制到帮助视图:

UITextView *helperTextView = [[UITextView alloc] init]; 
helperTextView = textView; //copy all attributes to the helperTextView; 

shadowTextView = [[UIView alloc] initWithFrame:textView.frame]; 
shadowTextView.backgroundColor = textView.backgroundColor; 
shadowTextView.layer.opacity = 1.0f; 
shadowTextView.layer.masksToBounds = NO; 
shadowTextView.layer.shadowColor = [UIColorFromRGB(0x00abff)CGColor]; 
shadowTextView.layer.shadowOpacity = 1.0f; 
shadowTextView.layer.shadowOffset = CGSizeMake(1.0f, 1.0f); 
shadowTextView.layer.shadowRadius = 10.0f; 
shadowTextView.layer.cornerRadius = 8.0f; 
shadowTextView.layer.shouldRasterize = YES; 

[self.view addSubview:shadowTextView]; 
[self.view addSubview:helperTextView];