WhWhen I implemented iAds on my Xcode 5, I decided to use auto-layout to show, and hide the iAd banner depending on whether ads are available or not. Here is a simple summary of my main view.
MainView
– HeaderView
– ContentsView
– BannerView
For auto-layout “height” settings, I only had it setup for HeaderView. Both ContentsView ad BannerView do not have “height” settings, but they do have settings on space to and from the nearest component, i.e. zero space in between. In my case, this resulted in having only the HeaderView and the ContentsView visible when I run the application.
Programmatically, I adjust the “height” constraint of the BannerView enabling my app to show/hide the ads. This is the code I use to adjust the “height” constraint to “0” if the banner is not loaded and to the correct banner height if the banner is loaded. bannerBox is my ADBannerView instance.
-(void)updateBanner {
// remove old height constraint
NSArray *constraints = [bannerView constraints];
for (NSLayoutConstraint *constraint in constraints) {
if (constraint.firstAttribute == NSLayoutAttributeHeight) {
[bannerView removeConstraint:constraint];
[bannerView setNeedsUpdateConstraints];
break;
}
}
if (bannerBox.bannerLoaded) {
// banner loaded
[bannerView setTranslatesAutoresizingMaskIntoConstraints:NO];
[bannerView addConstraint: [NSLayoutConstraint
constraintWithItem:bannerView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:bannerBox.bounds.size.height]];
}
else {
// banner not loaded
[bannerView setTranslatesAutoresizingMaskIntoConstraints:NO];
[bannerView addConstraint: [NSLayoutConstraint
constraintWithItem:bannerView
attribute:NSLayoutAttributeHeightrelatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:0]];
}
}
I then just call this updateBanner function in my implementation of didFailToReceiveAdWithError, bannerViewDidLoadAd., and didRotateFromInterfaceOrientation. If the app was able to get an ad, it shows the banner with the correct height depending on the iOS Device and the screen orientation. If there are no ads, it just hides the banner.
-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error {
NSLog(@"Error in Loading iAd banner!");
[self updateBanner];
}
-(void)bannerViewDidLoadAd:(ADBannerView *)banner {
NSLog(@"iAd banner loaded successfully!");
[self updateBanner];
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
NSLog(@"Loading didRotateFromInterfaceOrientation.");
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
[self updateBanner];
}
Hope this helps anybody trying to hide and show iAd banners with auto-layout. If you believe there is a better implementation for this, do let me know.