iosswiftuiviewviewdidloadviewdidlayoutsubviews

When does a UIView know how big it is?


I have a subclass of UIView that draws a picture onto itself using CAShapeLayers. I want the drawing to adapt to whatever size the UIView is given by AutoLayout. I gave it a drawGraph() function that gets its current size from .bounds.size and then draws a picture to fit.

I started by calling my drawing function in the container UIViewController's viewDidLoad(), but at that point the layout hasn't happened yet so it has whatever bounds it had in the storyboard.

I tried calling it from the view controller's viewDidLayoutSubviews(), but that isn't totally satisfactory either. It gets called twice: first with the bounds from the storyboard, then again with the updated (correct) bounds. There's a pause in between, so the draw and redraw is visible to the user.

How can I tell if a UIView has had its layout constraints applied and is ready to give me accurate dimensions?


Solution

  • You should draw it in UIView's drawRect(rect: CGRect). Once view needs to draw on screen, this function will be called.