Search code examples
iosswiftcore-graphicscalayer

CALayer sublayer not graceful during device rotation


I drew a circle directly on a view's layer, a device rotation looks perfect.

The drawing occurs in the func draw(_ rect: CGRect) method.

I then drew the circle on a sublayer and added it to the view in the init method.

I update the sub layer's frame in the func draw(_ rect: CGRect) method.

It seems to me like there are times that the sublayer is being updated before the device rotation is complete. Hence the first image below.

A quick fix to make this look a bit better is to clip the subview layers. This way the circle won't bleed to the main view (orange view).

Although this isn't fixing the main issue. I don't know why adding a sublayer is causing this issue.

I'm also drawing the content of the sublayer in the draw method of it's super view. The orange view is not the super view, the super view is the rectangle in the middle

During Rotation

During rotation

enter image description here

Note: I did not add example code because all examples that I have seen have the same issue. Others fix this by hardcoding the size of a view, hence the rotation will not resize the view and the rotation will not cause this. They also, tend to lock the view in portrait mode.

Although, if the example code is needed I can create a simple example.


Solution

  • I found a solution to the issue.

    It seems to me like everyone else has the same issues. This is because layers don't have constraints.

    We don't see these issues on production apps because apps are usually locked in portrait mode. It also seems like apple tends to use images for their controls and avoids drawing. This is according to a Ray Wenderlich article that I read.


    The solution is basically to use subviews (instead of sublayers) and use the layer built into the sub view to draw.

    This article explains the process: https://marcosantadev.com/calayer-auto-layout-swift/

    Here is an image showing the rotation with a subview and sublayers. The subview gracefully rotates because it has constraints. enter image description here