Adding auto-layout constraints programmatically
In my latest side-project, Martian Monster, I make use of Facebook’s open source library Shimmer to prettify a drop-down view.
The shimmer effect is added programmatically, via an FBShimmeringView. In my case, I wanted the UIButton that drops down from the top of the screen to shimmer, and so I added a shimmerView as a subview of the button and boom (if you looked closely, it’s shimmering.; I promise:
It all worked great.. that is until I turned my device into landscape mode:
As you can tell, the shimmerView does not adapt to the width of the screen like its superview (the UIButton) does. After some head scratching, I realized this is because the shimmerView was created programmatically and I hadn’t given it any information on how to adapt to auto-layout. Thus, I needed to add the necessary constraints to it (cue dramatic hamster) programmatically.
So, I used a helper method that would accept two parameters: a subview (to be constrained to the same size as its superview), and a superview:
And here’s how it looks when you call it:
[self constrainSubview:shimmeringView toSuperview:self.bannerButton];
The result was as desired; we see the shimmerView lays itself out to be the same size as its superview (the UIButton):
Hope this helps someone encountering a similar challenge.