Search code examples
iosswiftxcodeuitextviewshadow

Adding shadow to UITextView makes text expand out of UITextViewFrame


enter image description here

I have an UITextView and I wanna add shadow to it. The code I use is :

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

This code adds the shadow and makes the corners rounded but it also makes the text inside UITextView get out of textview frame. I tried adding

textview.clipToBounds = true

this sets the text inside but it removes the shadow. I've also tried setting :

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

and yet the problem repeats itself. I read somewhere here that I should set

textview.layer.shouldRasterize = true

It does nothing, just like seting it to false does nothing. So if anybody has any idea what would work, help me because I'm stuck.


Solution

  • Unfortunately if you use textview.clipsToBounds = true than your shadows will not be visible.

    What I recommend you do is set textview.clipsToBounds = true and the insert another UIView below the textview which has same frame as the textview and draw shadow and corner radius on that UIView.

    With that text from UITextView will not overflow it's bounds and you will have the shadow and corner radius visible...