How to autoresize sublayers

11,281

Solution 1

Its too late to answer...

But may be this can help others. There is no autoresize masks for CALayers You can manage that with some tricks..

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

This will work if you have created a subclass of UIView. If not that, you can just set the bounds to the frame of CALayer anywhere if you have reference to your layer.

Solution 2

At least there are 3 options:

  1. use delegate of CALayer
  2. override layoutSublayers, and call it by setNeedsLayout()
  3. use extension and call view's fitLayers

Example below, option 3:

Swift 5, 4

Code

extension UIView {
  func fitLayers() {
    layer.fit(rect: bounds)
  }
}

extension CALayer {
  func fit(rect: CGRect) {
    frame = rect

    sublayers?.forEach { $0.fit(rect: rect) }
  }
}

Example

// inside UIViewController 
override func viewWillLayoutSubviews() {    
  super.viewWillLayoutSubviews()

  view.fitLayers()
}

// or
// inside UIView
override func layoutSubviews() {    
  super.layoutSubviews()

  fitLayers()
}
Share:
11,281
Eager Beaver
Author by

Eager Beaver

Updated on July 04, 2022

Comments

  • Eager Beaver
    Eager Beaver almost 2 years

    I have an imageview and on button click I draw some bezier paths and some text layer too. On undo, I've removed last drawn path and text layer.

    Now I want to resize my image View to set up in uper half portion of view and duplicated in lower half view, and want to resize all layers at the same time and also want to continue drawing after that.

  • LE SANG
    LE SANG almost 11 years
    Thanks +1! it's work for me with: self.sublayer.frame = self.layer.bounds;
  • iTux
    iTux almost 4 years
    But it doesn't work with autolayouted view with CALayers while rotate :))
  • Michael N
    Michael N over 3 years
    Thank you! If you're going to use it in the UIView, you need to subclass UIView: import UIKit class CustomView : UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ override func layoutSubviews() { super.layoutSubviews() fitLayers() } }