Search code examples
iosswiftuitextview

Swift: How to get shadow working on UITextView from ViewDidLoad?


I'm unable to get the shadow on UITextView which is inside of a UIImageView.

I tried many possible ways. The constrain is, I cannot override layoutMethods as they are not accessible for some reason. So, for a demonstration, I've put the same code in viewDidLoad to debug but couldn't figure it out. Please explain what I'm doing wrong here.

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .black
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "guitar")
        imageView.layer.cornerRadius = 15
        imageView.clipsToBounds = true

        view.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.heightAnchor.constraint(equalToConstant: 240).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 240).isActive = true
        imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        let textView = UITextView(frame: CGRect.zero)
        textView.text = "This is a Sample text. This is a Sample text. This is a Sample text. This is a Sample text. This is a Sample text. "
        textView.isEditable = false
        textView.textAlignment = .left
        textView.isSelectable = false
        textView.backgroundColor = .systemBlue
        textView.textColor = UIColor.white
        textView.sizeToFit()
        textView.isScrollEnabled = false
        textView.textContainerInset = UIEdgeInsets(top: 6, left: 7, bottom: 6, right: 7)
        textView.clipsToBounds = false
        textView.layer.shadowColor = UIColor.gray.cgColor
        textView.layer.shadowRadius = 10
        textView.layer.opacity = 1
        textView.layer.shadowOffset = .zero
        textView.layer.shadowPath = UIBezierPath(rect: textView.bounds).cgPath
        textView.layer.masksToBounds = false

        imageView.addSubview(textView)
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.leftAnchor.constraint(equalTo: imageView.leftAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true
        textView.rightAnchor.constraint(equalTo: imageView.rightAnchor).isActive = true
    }

Solution

  • You set the LAYER opacity to 1:

    textView.layer.opacity = 1
    

    but you need to set the layer's shadowOpacity:

    //textView.layer.opacity = 1
    
    textView.layer.shadowOpacity = 1
    

    That should fix the issue.

    By the way, you get the same result with or without the .shadowPath (since the "default" shadow path is the bounds / rect of the view).

    enter image description here