Search code examples
iosuikituitextviewcagradientlayer

UITextView gradient layer apply not working


I want to apply gradient layer on top 10% and bottom 10% of UITextView. To do this, I place a dummy UIView called container view and make UITextView a subview of it. And then I add the following code:

   if let containerView = textView.superview {
        let gradient = CAGradientLayer(layer: containerView.layer)
        gradient.frame = containerView.bounds
        gradient.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
        gradient.locations = [0.0, 0.1, 0.9, 1.0]
        containerView.layer.mask = gradient
    } 

But the gradient is only applied to the top, not the bottom. Is there something wrong with the code?

Further, if I resize the container view anytime by modifying it's constraints, do I need to edit the mask layer every time?

Edit: Here is the output from @DonMag answer.

enter image description here

But what I want is something like in this image that text fades at the bottom.

enter image description here

EDIT2:

Here are screenshots after DonMag's revised answer.

enter image description here enter image description here


Solution

  • @DongMag solution is very complicated. Instead, you just need a mask implemented like:

    @IBDesignable
    class MaskableLabel: UILabel {
        var maskImageView = UIImageView()
    
        @IBInspectable
        var maskImage: UIImage? {
            didSet {
                maskImageView.image = maskImage
                updateView()
            }
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            updateView()
        }
    
        func updateView() {
            if maskImageView.image != nil {
                maskImageView.frame = bounds
                mask = maskImageView
            }
        }
    }
    

    Then with a simple gradient mask like this, You can see it even right in the storyboard.

    Preview

    Note: You can use this method and replace UILabel with any other view you like to subclass.

    Here is the example project on the GitHub