I had a similar problem - needing to set the frame of a 'CALayer' when using auto layout with views (in code, not IB).
In my case, I had a slightly convoluted hierarchy, having a view controller within a view controller. I ended up at this SO question and looked into the approach of using viewDidLayoutSubviews
. That didn't work. Just in case your situation is similar to my own, here's what I found...
Overview
I wanted to set the frame for the CAGradientLayer
of a UIView
that I was positioning as a subview within a UIViewController
using auto layout constraints.
Call the subview gradientView
and the view controller child_viewController
.
child_viewController
was a view controller I'd set up as a kind of re-usable component. So, the view
of child_viewController
was being composed into a parent view controller - call that parent_viewController
.
When viewDidLayoutSubviews
of child_viewController
was called, the frame
of gradientView
was not yet set.
(At this point, I'd recommend sprinkling some NSLog
statements around to get a feel for the sequence of creation of views in your hierarchy, etc.)
So I moved on to try using viewDidAppear
. However, due to the nested nature of child_viewController
I found viewDidAppear
was not being called.
(See this SO question: viewWillAppear, viewDidAppear not being called, not firing).
My current solution
I've added viewDidAppear
in parent_viewController
and from there I'm calling viewDidAppear
in child_viewController
.
For the initial load I need viewDidAppear
as it's not until this is called in child_viewController
that all of the subviews have their frames set. I can then set the frame for the CAGradientLayer
...
I've said that this is my current solution because I'm not particularly happy with it.
After initially setting the frame of the CAGradientLayer
- that frame can become invalid if the layout changes - e.g. rotating the device.
To handle this I'm using viewDidLayoutSubviews
in child_viewController
- to keep the frame of the CAGradientLayer
within gradientView
, correct.
It works but doesn't feel good.
(Is there a better way?)