Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CALayers didn't get resized on its UIView's bounds change. Why?

I have a UIView which has about 8 different CALayer sublayers added to its layer. If I modify the view's bounds (animated), then the view itself shrinks (I checked it with a backgroundColor), but the sublayers' size remains unchanged.

How to solve this?

like image 549
Geri Borbás Avatar asked Mar 23 '10 22:03

Geri Borbás


4 Answers

I used the same approach that Solin used, but there's a typo in that code. The method should be:

- (void)layoutSubviews {
  [super layoutSubviews];
  // resize your layers based on the view's new bounds
  mylayer.frame = self.bounds;
}

For my purposes, I always wanted the sublayer to be the full size of the parent view. Put that method in your view class.

like image 61
Chadwick Wood Avatar answered Oct 20 '22 20:10

Chadwick Wood


Since CALayer on the iPhone does not support layout managers, I think you have to make your view's main layer a custom CALayer subclass in which you override layoutSublayers to set the frames of all sublayers. You must also override your view's +layerClass method to return the class of your new CALayer subclass.

like image 36
Ole Begemann Avatar answered Oct 20 '22 21:10

Ole Begemann


I used this in the UIView.

-(void)layoutSublayersOfLayer:(CALayer *)layer
{
    if (layer == self.layer)
    {
        _anySubLayer.frame = layer.bounds;
    }

super.layoutSublayersOfLayer(layer)
}

Works for me.

like image 17
Runo Sahara Avatar answered Oct 20 '22 21:10

Runo Sahara


I had the same problem. In a custom view's layer I added two more sublayers. In order to resize the sublayers (every time the custom view's boundaries change), I implemented the method layoutSubviews of my custom view; inside this method I just update each sublayer's frame to match the current boundaries of my subview's layer.

Something like this:

-(void)layoutSubviews{
   //keep the same origin, just update the width and height
   if(sublayer1!=nil){
      sublayer1.frame = self.layer.bounds;
   }
}
like image 9
Solin Avatar answered Oct 20 '22 21:10

Solin