向 UITextView 添加阴影会使文本扩展到 UITextViewFrame 之外

Adding shadow to UITextView makes text expand out of UITextViewFrame

我有一个 UITextView,我想给它添加阴影。我使用的代码是:

textview.layer.shadowColor = UIColor.lightGray.cgColor
textview.layer.shadowOffset = CGSize(width:0,height: 2.0)
textview.layer.shadowRadius = 2.0
textview.layer.shadowOpacity = 1.0
textview.layer.masksToBounds = false
textview.layer.cornerRadius = 5

此代码添加了阴影并使边角变圆,但它也使 UITextView 中的文本脱离了 textview 框架。 我尝试添加

textview.clipToBounds = true

这会在内部设置文本,但会移除阴影。我也试过设置 :

textview.layer.maskToBounds = true
textview.clipToBounds = false

但问题再次出现。 我在这里的某个地方读到我应该设置

textview.layer.shouldRasterize = true

它什么都不做,就像将它设置为 false 什么都不做一样。 因此,如果有人知道什么可行,请帮助我,因为我被卡住了。

不幸的是,如果您使用 textview.clipsToBounds = true,您的阴影将不可见。

我建议你做的是设置 textview.clipsToBounds = true 并在 textview 下面插入另一个 UIViewtextview 具有相同的框架并绘制阴影和角半径在那 UIView 上。

来自 UITextView 的文本不会溢出它的边界,您将看到阴影和角半径...