Automatically resize CALayer in iOS when changing device orientation

I added another CALayer for the custom view, the code

hostedGraphLayer.frame = self.layer.bounds; [self.layer addSublayer:hostedGraphLayer]; 

When the device orientation changes, the layer of the layer sublevel also rotates, but it does not autoresist in relation to the view. Layer does not have an autoresize property for iOS.

One of the answers already in stackOverFlow CALayers has not changed in accordance with the change in the boundaries of the UIView. Why? In this case, changing the layer frame when changing the orientation of the device, the layer will not autoresist in relation to its representation between the beginning and end of rotation, this can be clearly seen in the simulator by switching the slow animation.

Is there any correction for this: "When the view is rotated, its layers also rotate, and it must resize wrt of its view."

+6
source share
2 answers

No, there is no fix. Nonetheless,

You must change your frames.

correct me if I am wrong.

0
source

In the view attribute inspector, set the view mode for redrawing.
View attributes inspector
The content will no longer adapt or align or even stretch, but will be displayed along the animation.

What really happens is that it displays the final position and that the render is stretched during the animation, but this is a trick quite invisible to the user :)

The three above will call setNeedsDisplay on the background layer ( view.layer ) when the view frame changes , but you need to update its children . setNeedsDisplay layer will not propagate to sublayers.
Also, these sublayers will not autoresist as representations.
If you really want this behavior, use views instead or force yourself to redraw yourself by overriding the setNeedsDisplay method of the parent layer.

 -(void)setNeedsDisplay { [super setNeedsDisplay]; for (CALayer *sublayer in self.sublayers) { [sublayer setNeedsDisplay]; } } 

It all depends on what / how you need to redraw.

If you really want to use a layer as a background layer that matches the frame of your view, subclass UIView and override its class method +(Class)layerClass to return the class of your class.

 +(Class)layerClass { return [MyCustomLayer class]; } 

It will use your custom layer as the default background layer.
It is very powerful;) I use it everywhere. Do not forget the Redraw attribute!

-1
source

All Articles