Search code examples
iosswiftuiviewcalayer

How to make a fade out border for uiview


How to implement a one-side and fade out border for UIView. I'm sorry that I don't have enough reputation to post a screenshot. But there is an example in iOS native Contact app. If you click on "+" then "add phone", there will be a vertically line, which is exactly what I want.

I have already implemented one-side border for an UIView but can't find out a way to make it fade out. I tried CIFilter, which didn't work. Then I noticed that this fade out effect is simliar to shadow. I tried to simulate the fade out by setting shadow but failed again.

Thanks for any answer and suggestion in advance.


Solution

  • You could use a CAGradientLayer:

    let layer = CAGradientLayer()
    layer.colors = [UIColor.white.cgColor, UIColor.gray.cgColor]
    // play around with layer.locations and layer.{startPoint|endPoint} to suit your needs
    

    You can then subclass UIView and override its layerClass to return the gradient layer, and then size and position that view as you please:

    override class func layerClass() -> AnyClass {
       return CAGradientLayer.self
    }
    // configure the layer with color, end/start and locations in init()
    

    This allows you to drop that view in anywhere and use auto layout to size and position it as you please.