1

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?

Robert
  • 6,660
  • 5
  • 39
  • 62

2 Answers2

1

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

Lumialxk
  • 6,239
  • 6
  • 24
  • 47
1

In my subclasses of UIView I usually do the code related to layout by overriding the layoutSubview() method. If I remember correctly it's more lightweight than drawRect(rect: CGRect).

But if you're really doing only drawing then you should probably do it in drawRect(rect: CGRect), as that's what Xcode suggests you when you create a new UIView subclass.

Andrej
  • 7,266
  • 4
  • 38
  • 57