使用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. 这是我输出的上述代码。

在此处输入图像描述

但是当我尝试向myTextView添加文本时,我的myTextView文本超出了界限,它看起来像myTextView如下所示。

在此处输入图像描述

只有当我添加阴影时才会发生这种情况 。 textView里面的文字没有显示怪异如果我不加阴影。我做错了什么? 我怎么能克服这个? 为什么会这样?

更新:

@borrrden说我发现它正在发生,因为设置了maskToBounds = NO; 如果我们设置为YES那么我们就无法获得阴影。 原因这是一个答案

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

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

只需在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]; 

除了上一个答案,只需将原始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];