I have a UIViewController where I am adding a CALayer subclass to the view's layer:
[self.view.layer addSublayer:myObject.backgroundLayer];
When I rotate the device, the view rotates, but the CALayer doesn't. It sort of gets shunted off to the left, still in portrait view.
Is there a way to make sublayers rotate automatically or do I need to apply a transform?
You need to manage the rotation of the CALayer yourself. I believe that 0,0 stays at the same place and that the size is changed to match the new orientation, so if you wanted to do something yourself, you'd need to manage the addition of the rotation transformation yourself.
With Swift 4 / iOS 11, according to your needs, you may choose one of the 6 following examples in order to manage your
CALayer
/CAGradientLayer
frame upon a device rotation.The examples below use
CAGradientLayer
but can easily be mapped toCALayer
orCAShapeLayer
cases.#1. Overriding
UIViewController
viewDidLayoutSubviews()
#2. Overriding
UIViewController
loadView()
, subclassingUIView
and overridingUIView
layoutSubviews()
LayerView.swift
LayerView.swift (alternative)
ViewController.swift
#3. Using Key Value Observing (KVO)
#4. Overriding
UIViewController
loadView()
, subclassingUIView
and overridingUIView
layerClass
LayerView.swift
ViewController.swift
#5. Overriding
UIViewController
loadView()
, subclassingUIView
and overridingCALayerDelegate
layoutSublayers(of:)
LayerView.swift
ViewController.swift
#6. Overriding
UIViewController
loadView()
, subclassingUIView
, overridingUIView
layerClass
, subclassingCALayer
and overridingCALayer
layoutSublayers()
Layer.swift
LayerView.swift
ViewController.swift
Sources: