Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear and redraw contents of a UIView (present inside a view controller) with swift?

I've a UIView inside a View Controller in which I'm drawing few lines as required by my app. After a certain point of time, I want some of those lines to disappear and a few other to appear in the same view. Approach I'm using as of now is that I'm clearing the UIView and redrawing all the lines I want to draw in the updated view.

Can somebody tell me what's the right way to go about it? I've gone through various questions that sound similar but it hasn't helped much. Till now I've tried things like:-

outletView.setNeedsDisplay()

and

let context = UIGraphicsGetCurrentContext()
context?.clear(outletView.frame)

None of these seem to make any difference.

If I call viewDidLoad() again since all the lines are updated now. New lines to be drawn come up but the ones that were supposed to disappear don't go away. Variables for lines are updated correctly since other logic I have which checks line variable's values is working fine after the update is supposed to happen. Only problem is with the redraw part. In fact, if I understand this correctly, problem is only with cleaning the old uiview contents. If cleaning happens properly, redraw with viewDidLoad will show correct lines drawn.

P.S. I know that calling viewDidLoad() explicitly isn't a good practice. Hope to find a solution to this problem without having to call viewDidLoad again.

like image 895
hellSigma Avatar asked Jan 05 '17 06:01

hellSigma


1 Answers

Maybe you could draw your lines in different layers of the view, delete the layer containing the lines that need to disappear and create a new layer for the new lines. You can draw in layoutSubviews() and use self.setNeedsLayout() when you need to update the view.

remove:

guard let sublayers = yourView.layer.sublayers else { return }
        for layer in sublayers {
            layer.removeFromSuperlayer()
        }

add:

let linesPath = UIBezierPath()
let linesLayer = CAShapeLayer()
linesPath.move(to: CGPoint(x: 0, y: 0)
linesPath.addLine(to: CGPoint(x: 50, y: 100)
lineLayer.path = linesPath.cgPath
linesLayer.lineWidth = 1.0
linesLayer.strokeColor = UIColor.black
yourView.layer.addSublayer(linesLayer)
like image 76
Ocunidee Avatar answered Nov 07 '22 22:11

Ocunidee