ios – Creating a gradient border of uiview with fewer crashes


I have this custom code that i wrote awhile back in order to have a gradient border on my views. Only problem is, it has slowly become my top crash in my app.

The crashlog I am getting in crashlytics points to the line super.layoutSubviews() which doesn’t make much sense to me.

Anyone have any idea on improvements, or a different approach to doing this same thing, that can lead to fewer crashes? I get 120-200 a week from this view.

class GradientBorderView: UIView {
    var enableGradientBorder: Bool = false

    var borderGradientColors: [UIColor] = [] {
        didSet {
            setNeedsLayout()
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        guard enableGradientBorder && !borderGradientColors.isEmpty  else {
            layer.borderColor = nil
            return
        }
        let gradient = UIImage.imageGradient(bounds: bounds, colors: borderGradientColors)
        layer.borderColor = UIColor(patternImage: gradient).cgColor
    }
}


extension UIImage {

    static func imageGradient(bounds: CGRect, colors: [UIColor]) -> UIImage {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        gradientLayer.colors = colors.map(\.cgColor)

        // This makes it left to right, default is top to bottom
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)

        let renderer = UIGraphicsImageRenderer(bounds: bounds)

        return renderer.image { gradientLayer.render(in: $0.cgContext) }
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img