Programmatically adding a view between a tableView and bottomLayoutGuide - ios

I have a UIViewController with a UITableView that fills the screen for an ad-supported version. MyViewController is embedded in a UINavigationController and it has a UITabBarController at the bottom.
There will be 2 versions of this app:
1) Paid - I have this configured on a storyboard. It works as desired.
2) Ad Supported - Try as I may, I can't get the banner to draw in the right spot. I'm trying to do this:
topLayoutGuide
tableview
standard height padding
bannerView (50 height)
standard height padding
bottomLayoutGuide
Instead, the bannerView is being drawn on top of the tableView, rather than between the tableView and the bottomLayoutGuide
I call a method I created called configureBannerView from viewDidLoad. Here' the relevant portion of the code that lays out the view in Visual Format Language:
var allConstraints = [NSLayoutConstraint]()
let horizontalTableViewConstraint = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|[tableView]|",
options: NSLayoutFormatOptions.AlignAllCenterY,
metrics: nil,
views: views)
allConstraints += horizontalTableViewConstraint
let horizontalBannerViewConstraint = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|[leftBannerViewSpacer]-[bannerView(320)]-[rightBannerViewSpacer(==leftBannerViewSpacer)]|",
options: NSLayoutFormatOptions.AlignAllCenterY,
metrics: nil,
views: views)
allConstraints += horizontalBannerViewConstraint
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[topLayoutGuide][tableView]-[leftBannerViewSpacer(50)]-[bottomLayoutGuide]|",
options: [],
metrics: metrics,
views: views)
allConstraints += verticalConstraints
I can't figure out why this isn't working. Below is the complete configureBannerView method.
func configureBannerView() {
if adSupported == false {
// Do nothing, leave it alone
} else {
// remove existing constraints
tableView.removeConstraints(tableView.constraints)
tableView.translatesAutoresizingMaskIntoConstraints = false
// create dictionary of views
var views: [String : AnyObject] = [
"tableView" : tableView,
"topLayoutGuide": topLayoutGuide,
"bottomLayoutGuide": bottomLayoutGuide]
// Create a frame for the banner
let bannerFrame = CGRect(x: 0, y: 0, width: kGADAdSizeBanner.size.width, height: kGADAdSizeBanner.size.height)
// Instnatiate the banner in the frame you just created
bannerView = GADBannerView.init(frame: bannerFrame)
bannerView?.translatesAutoresizingMaskIntoConstraints = false
// add the bannerView to the view
view.addSubview(bannerView!)
// add bannerView to the view dictionary
views["bannerView"] = bannerView
// Create spacers for left and right sides of bannerView
// 32.0 = leftSpacer left pad + leftSpacer right pad + rightSpacer left pad + rightSpacer right pad
// Calculate width of spacer
let spacerWidth = (screenSize.width - kGADAdSizeBanner.size.width - 32.0) / 2
// Instantiate left and right pads
// 50.0 = height of bannerView
let leftBannerViewSpacer = UIView(frame: CGRect(x: 0, y: 0, width: spacerWidth, height: 50.0))
let rightBannerViewSpacer = UIView(frame: CGRect(x: 0, y: 0, width: spacerWidth, height: 50.0))
leftBannerViewSpacer.translatesAutoresizingMaskIntoConstraints = false
rightBannerViewSpacer.translatesAutoresizingMaskIntoConstraints = false
// add the spacers to the subview
view.addSubview(leftBannerViewSpacer)
view.addSubview(rightBannerViewSpacer)
// add to the views dictionary
views["leftBannerViewSpacer"] = leftBannerViewSpacer
views["rightBannerViewSpacer"] = rightBannerViewSpacer
// Create metric for tabBarHeight
let tabBarHeight = tabBarController?.tabBar.frame.height
// Create a dictionary of metrics
let metrics: [String : CGFloat] = ["tabBarHeight": tabBarHeight!]
var allConstraints = [NSLayoutConstraint]()
let horizontalTableViewConstraint = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|[tableView]|",
options: NSLayoutFormatOptions.AlignAllCenterY,
metrics: nil,
views: views)
allConstraints += horizontalTableViewConstraint
let horizontalBannerViewConstraint = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|[leftBannerViewSpacer]-[bannerView(320)]-[rightBannerViewSpacer(==leftBannerViewSpacer)]|",
options: [NSLayoutFormatOptions.AlignAllCenterY],
metrics: nil,
views: views)
allConstraints += horizontalBannerViewConstraint
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[topLayoutGuide][tableView]-[leftBannerViewSpacer(50)]-[bottomLayoutGuide]|",
options: [],
metrics: metrics,
views: views)
allConstraints += verticalConstraints
NSLayoutConstraint.activateConstraints(allConstraints)
Thank you for reading. I welcome suggestions to resolve my erroneous code.

Storyboard solution
Do not add constraints programmatically unless all other avenues have failed: there is no way to see what you are doing until you build, link, run.
A much simpler solution requiring much less code is to hold on to references of your views an constraints from Interface Builder, and:
constraintToTweak.constant = newValue
Unlike the other properties, the constant may be modified after constraint creation. Setting the constant on an existing constraint performs much better than removing the constraint and adding a new one that's just like the old but for having a new constant.
or
constraintToTweak.active = false
The receiver may be activated or deactivated by manipulating this property.  Only active constraints affect the calculated layout.  Attempting to activate a constraint whose items have no common ancestor will cause an exception to be thrown. Defaults to NO for newly created constraints.

With ishaq's and SwiftArchitect's assistance, I figured it out. It turns out, the key to getting the GADBannerView to display properly below a UITableView without adding it as a footer was super simple. I ended up chopping 100 lines of needless code by doing the following:
1) UIStackView: If you haven't used this before, stop what you're doing now and follow this tutorial.
I added my tableView: UITableView and the bannerView: GADBannerView in interface builder to a vertical UIStackView
2) I created IBOutlets (I had tableView already) for both of them on MyViewController.
3) My refactored configureBannerView looks like this.
// I added these properties at the top. I did not know you could drag
// constraints from Interface Builder onto the ViewController
#IBOutlet weak var bannerViewHeight: NSLayoutConstraint!
#IBOutlet weak var bannerViewWidth: NSLayoutConstraint!
func configureBannerView() {
if adSupported == true {
loadAd() // follow Google's documentation to configure your requests
} else {
bannerView.hidden = true // this hides the bannerView if it's not needed
// Removes constraint errors when device is rotated
bannerViewWidth.constant = 0.0
bannerViewHeight.constant = 0.0
}
}
Thanks to ishaq & SwiftArchitect for pointing me in the right direction.

Add a new adMob UIViewController as root controller and addSubview of the old root controller.
I had a programmatic very similar problem case having to add adMob to a UITabBarController root controller with tab Controllers that were UINavigationController. Them all making hard resistance in trying to resize them internally, the ads were just typed over the application views. I might have just not been lucky enough finding a working way that path. Read a lot Stackoverflow and Google hints.
I also believe Apples and Googles recommendations are like having the ads below and kind of separate from but tight to the app. The Android Admob banners appears the same way, and same behavior is wanted. (Did the same project for Android recently).
Make a new app root controller, a ViewController with Admob
To be reusable and smoothly implementable in future projects, about a new adUnitID is all needed to be put in (and the name of the old root controller). The banner will be below the applications screen.
Just add this class file to the project and make it the root controller in the AppDelegate.swift file.
import UIKit
import GoogleMobileAds
class AdsViewController: UIViewController, GADBannerViewDelegate {
let adsTest = true
let ads = true //false //
let adUnitIDTest = "ca-app-pub-3940256099942544/2934735716"
let adUnitID = "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx"
let tabVc = MainTabBarController()
var bannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
// Add the adMob banner
addBanner(viewMaster: view)
// Add the old root controller as a sub-view
view.addSubview(tabVc.view)
// Make its constraints to fit the adMob
if(ads) {
tabVc.view.translatesAutoresizingMaskIntoConstraints = false
tabVc.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tabVc.view.bottomAnchor.constraint(equalTo: bannerView.topAnchor).isActive = true
tabVc.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tabVc.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
// To be notified of rotation
NotificationCenter.default.addObserver(self, selector: #selector(AdsViewController.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
}
}
/*******************************
Ads banner standard engine
*******************************/
func addBanner(viewMaster: UIView) {
if(ads) {
// We instantiate the banner with desired ad size.
bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
addBannerViewToView(bannerView, viewMaster: viewMaster)
if(adsTest) {
bannerView.adUnitID = adUnitIDTest
} else {
bannerView.adUnitID = adUnitID
}
bannerView.rootViewController = self
bannerView.load(GADRequest())
bannerView.delegate = self
}
}
func addBannerViewToView(_ bannerView: GADBannerView, viewMaster: UIView) {
bannerView.translatesAutoresizingMaskIntoConstraints = false
viewMaster.addSubview(bannerView)
viewMaster.addConstraints(
[NSLayoutConstraint(item: bannerView,
attribute: .bottom,
relatedBy: .equal,
toItem: viewMaster.safeAreaLayoutGuide,
attribute: .bottom,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: bannerView,
attribute: .centerX,
relatedBy: .equal,
toItem: viewMaster,
attribute: .centerX,
multiplier: 1,
constant: 0)
])
}
/*******************************
Rotation (change SmartBanner)
*******************************/
#objc func rotated() {
if UIDevice.current.orientation.isPortrait {
bannerView.adSize = kGADAdSizeSmartBannerPortrait
}
if UIDevice.current.orientation.isLandscape {
bannerView.adSize = kGADAdSizeSmartBannerLandscape
}
}
}

Related

NSLayoutConstraint with VFL is working only horizontally when using '|'

I have the following implementation of a UIView..
struct LoginView {
let loginView: UIView = UIView()
func layoutLoginView() -> UIView {
loginView.translatesAutoresizingMaskIntoConstraints = false
loginView.backgroundColor = UIColor.purple
return loginView
}
}
Then, I subview the above in the viewcontroller as below..
class LoginVC: UIViewController {
private let instanceOfLoginView = LoginView()
override func loadView() {
super.loadView()
view.addSubview(instanceOfLoginView.layoutLoginView())
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[loginView]-|", options: [], metrics: [:], views: ["loginView":instanceOfLoginView.layoutLoginView()]))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[loginView]-|", options: [], metrics: [:], views: ["loginView":instanceOfLoginView.layoutLoginView()]))
}
The problem is that only the 'H' side of the NSLayout is working -check the screenshot below-. The 'V' is not working.
However, when I apply the following "V:|-8-[loginView]-8-|", it works!!!
Could you advise why doesn't the "V:|-[loginView]-|" simply work, please..?
Appreciate your help!
When using VFL, the - character means "use the standard spacing".
In your case:
"H:|-[loginView]-|"
"V:|-[loginView]-|"
you are saying "use the layout margins" which are, by default:
UIEdgeInsets(top: 0.0, left: 16.0, bottom: 0.0, right: 16.0)
Prior to iOS 11 the .layoutMargins of the root view managed by a view controller cannot be changed. To get your purple view to cover the full view, change your VFL to:
"H:|[loginView]|"
"V:|[loginView]|"

UIScrollView does not fit with constraints

I'd like to use a scrollView to move the nested view content up when the keyboard appears. (Maybe you know a better solution ?)
So, I put a UIScrollView into my UIViewController and a UIImageView into my UIScrollView. The problem is my UIScrollView is as large as my image size despite constraints.
I put the following constraints :
scrollView.addConstraintsWithFormat(format: "H:|[v0]|", views: backgroundImage)
scrollView.addConstraintsWithFormat(format: "V:|[v0]|", views: backgroundImage)
self.view.addConstraintsWithFormat(format: "H:|[v0]|", views: scrollView)
self.view.addConstraintsWithFormat(format: "V:|[v0]|", views: scrollView)
Someone have a solution ?
This is my full UIViewController code :
import UIKit
class HomeViewController: UIViewController {
let scrollView: UIScrollView = {
let screenSize = UIScreen.main.bounds
let scrollView = UIScrollView()
scrollView.backgroundColor = .red
scrollView.contentSize = CGSize(width: screenSize.width, height: screenSize.height)
return scrollView
}()
let backgroundImage: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "BACKGROUND_ASIA")
imageView.alpha = 0.5
return imageView
}()
override func viewDidLoad() {
setupHomeView()
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setupHomeView() {
self.view.backgroundColor = UIColor.black
self.view.addSubview(scrollView)
self.view.addConstraintsWithFormat(format: "H:|[v0]|", views: scrollView)
self.view.addConstraintsWithFormat(format: "V:|[v0]|", views: scrollView)
scrollView.addSubview(backgroundImage)
scrollView.addConstraintsWithFormat(format: "H:|[v0]|", views: backgroundImage)
scrollView.addConstraintsWithFormat(format: "V:|[v0]|", views: backgroundImage)
}
}
extension UIView {
func addConstraintsWithFormat(format: String, views: UIView...) {
var viewsDictionary = [String: UIView]()
for (index, view) in views.enumerated() {
let key = "v\(index)"
viewsDictionary[key] = view
view.translatesAutoresizingMaskIntoConstraints = false
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
}
}
You should call super first in viewDidLoad.
You should read up on how scrollViews work.
Here's what you need:
The ScrollView needs constraints for left/right/top/bottom.
This will determine the size of the presentable portion of the scrollview. This is the part that you would resize when the keyboard shows.
Then, you need to set the size of the ScrollView's content. This is the content that can be scrolled. You will need to manually set the size of your imageView, or setup equality between your imageView and views that exist outside of your scrollview. (eg imageView.width == view.width).
Hope this points in the right direction. You might want to consider using Interface Builder to set this up so you can see all the constraints and get warning when things aren't set up properly.
Thanks for your answer PEEJWEEJ, but I found another alternative to my problem. I used the NotificationCenter to notify keyboard opening and I made a view.animate() to scroll my view. By this way I avoid to use a scrollView or a tableView.

NSConstraints crashes app after second load of UIView

I've got a custom UIView that I instantiate in a view controller with this function, displayedTimer is an iVar of the view controller:
func changeViewModeTo(mode: String){
if mode == "settings" {
addSettingsModeConstraints()
animatedLayoutIfNeeded(removeView: true)
}
if mode == "timer" {
displayedTimer = TimerView.init()
displayedTimer.frame = CGRect(x: (self.view.bounds.size.width)/2 - 50, y: (self.view.bounds.size.height)/2 - 80, width: 100, height: 160)
let colors = timer.getColorScheme()
displayedTimer.setColorScheme(colorLight: colors["lightColor"]!, colorDark: colors["darkColor"]!)
displayedTimer.setTimeRemainingLabel(timer.duration)
displayedTimer.setCountDownBarFromPercentage(1.0)
displayedTimer.layer.zPosition = 100 //make sure the timer view sits on top of the settings panel
displayedTimer.timerLabel.hidden = false
displayedTimer.translatesAutoresizingMaskIntoConstraints = false
let pinchGestureRecogniser = UIPinchGestureRecognizer(target: self, action: #selector(self.pinchDetected(_:)))
displayedTimer.addGestureRecognizer(pinchGestureRecogniser)
self.view.addSubview(displayedTimer)
addTimerModeConstraints()
animatedLayoutIfNeeded(removeView: false)
}
}
If the mode is set to timer then it creates a subclass of UIView and sets an instance variable to it, constraints are added to make it full screen and then an animated layoutIfNeeded() is called. If the mode being set is settings then it deactivates the timerConstraints, adds new constraints to shrink the view, calls an animated layoutIfNeeded and then removes the view from the superView.
func animatedLayoutIfNeeded(removeView removeView: Bool){
UIView.animateWithDuration(0.2, delay: 0, options: [UIViewAnimationOptions.CurveEaseIn] , animations: {
self.view.layoutIfNeeded()
}) { (true) in
if removeView == true {
self.displayedTimer.removeFromSuperview()
}
}
}
The constraints are added and removed with these methods (settingsConstraints and timerConstraints are iVars of the view controller):
//MARK: - Layout Constraints
func addSettingsModeConstraints() {
let views = ["timerView": displayedTimer]
let timerHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-75-[timerView]-75-|",
options: [],
metrics: nil,
views: views)
settingsConstraints += timerHorizontalConstraints
let timerVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-105-[timerView]-85-|",
options: [],
metrics: nil,
views: views)
settingsConstraints += timerVerticalConstraints
NSLayoutConstraint.deactivateConstraints(timerConstraints)
NSLayoutConstraint.activateConstraints(settingsConstraints)
}
func addTimerModeConstraints() {
let views = ["timerView": displayedTimer]
let timerHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-0-[timerView]-0-|",
options: [],
metrics: nil,
views: views)
timerConstraints += timerHorizontalConstraints
let timerVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-0-[timerView]-0-|",
options: [],
metrics: nil,
views: views)
timerConstraints += timerVerticalConstraints
NSLayoutConstraint.activateConstraints(timerConstraints)
}
changeViewModeTo is called from a pinch gesture recogniser (negative pinch sets one mode, positive pinch sets another mode).
The first time I pinch, the view is created and goes full screen. I then reverse pinch and the view shrinks and is removed. Then when I pinch again to start the process over the app crashes, there are no console errors but there is a red error over the line of code: NSLayoutConstraint.activateConstraints(timerConstraints)
I'm guessing removing the subview has caused the reference to NSConstraints to disappear?
Any thoughts would be great as I can't figure it out.
So turns out this is a simple fix, call removeAll() on settingsConstraints and timerConstraints before recreating them and activating them solves the problem.

Programmatically Added Constraint Not Working

I've been trying to add constraints programmatically to a view that I'm also adding programmatically to my view controller. However, it seems like the constraints are not being followed.
The view has been added to the story board for the view controller, but isn't actually added to the view controller's view until later on (See screenshot below).
I've tried adding a variety of constraints but none of them have worked so far. I've simplified it now to the single constraint below and even this will not work. What am I doing wrong?
#IBOutlet var loadingView: LoadingView!
override func viewDidLoad() {
super.viewDidLoad()
displayLoadingView(true)
}
func displayLoadingView(display: Bool) {
if display {
view.addSubview(loadingView)
let widthConstraint = NSLayoutConstraint(item: loadingView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50.0)
view.addConstraint(widthConstraint)
}
}
set translatesAutoresizingMaskIntoConstraints = false to any view you are settings constraints programatically.
from the apple doc: translatesAutoresizingMaskIntoConstraints
If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to false, and then provide a non ambiguous, nonconflicting set of constraints for the view.
You don't set all necessary constraints, that can be the reason. Consider following rough example. MyView interface is defined in standalone xib file. Hope it helps:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let myView = loadFromNib("MyView") else {
return
}
view.addSubview(myView)
myView.translatesAutoresizingMaskIntoConstraints = false
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[myView]-15-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["myView": myView]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-15-[myView]-15-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["myView": myView]))
}
func loadFromNib(cls: String) -> UIView? {
return NSBundle.mainBundle().loadNibNamed(cls, owner: nil, options: nil)[0] as? UIView
}
}

Display ADBannerView with UITableViewController inside UITabBarController

EDIT
Thanks to #LeoNatan I have now got a complete working solution. If anyone finds this and would like the solution, it's available on GitHub.
Original Question
I'm trying to get iAds (or any other view for that matter, although it may be specific to ADBannerView) to be displayed just above a UITabBar. I've gone about a few different ways of doing this, but haven't come up with a solution that satifies the following:
Works on iOS 7 and 8
Works with and without the iAd displayed
Works in landscape and portrait
Works on iPhone and iPad
UITableViews insets correctly update
The only solution I have so far that has worked has been to have my UITableView inside a UIViewController, and adding the UITableView and ADBannerView to the view property of the UIViewController. I moved away from this for 2 reasons:
The UITableView did not extend its edges below the bottom UITabBar
I need to subclass UITableViewController, not UIViewController
I have a bannerView property on my AppDelegate and a shouldShowBannerView property to decide whether or not to show the iAd, and share a single instance. The AppDelegate then sends out notifications when iAds should be displayed or hidden (i.e., when an iAd is loaded and when the user has paid to remove the iAds). The "base" of the code works as such:
func showiAds(animated: Bool) {
if !self.showingiAd {
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
if let bannerView = delegate.bannerView {
println("Showing iAd")
self.showingiAd = true
if (bannerView.superview != self.view) {
bannerView.removeFromSuperview()
}
// let bannersSuperview = self.view.superview! // Bottom inset incorrect
let bannersSuperview = self.view // Banner is shown at the top screen. Crashes on iOS 7 (at bannersSuperview.layoutIfNeeded())
// let bannersSuperview = self.tableView // The is the same as self.view (duh)
// let bannersSuperview = self.tabBarController!.view // Bottom inset incorrect
// Added the view and the left/right constraints allow for the proper height
// to be returned when bannerView.frame.size.height is called (iOS 7 fix mainly)
bannersSuperview.addSubview(bannerView)
bannersSuperview.addConstraints([
NSLayoutConstraint(item: bannerView, attribute: .Left, relatedBy: .Equal, toItem: bannersSuperview, attribute: .Left, multiplier: 1, constant: 0),
NSLayoutConstraint(item: bannerView, attribute: .Right, relatedBy: .Equal, toItem: bannersSuperview, attribute: .Right, multiplier: 1, constant: 0),
])
bannersSuperview.layoutIfNeeded()
let bannerViewHeight = bannerView.frame.size.height
var offset: CGFloat = -self.bottomLayoutGuide.length
if (UIDevice.currentDevice().systemVersion as NSString).floatValue < 8 {
// Seems to be needed for some reason
offset -= bannerViewHeight
}
let bannerBottomConstraint = NSLayoutConstraint(item: bannerView, attribute: .Bottom, relatedBy: .Equal, toItem: bannersSuperview, attribute: .Bottom, multiplier: 1, constant: offset + bannerViewHeight)
// self.bannerBottomConstraint = bannerBottomConstraint
bannersSuperview.addConstraint(bannerBottomConstraint)
bannersSuperview.layoutSubviews()
// bannerSuperview.setNeedsLayout()
bannersSuperview.layoutIfNeeded()
// Previously, this values was the height of the banner view, so that it starts off screen.
// Setting this to 0 and then doing an animation makes it slide in from below
bannerBottomConstraint.constant = offset
bannersSuperview.setNeedsUpdateConstraints()
UIView.animateWithDuration(animated ? 10 : 0, animations: { () -> Void in
// Calling layoutIfNeeded here will animate the layout constraint cosntant change made above
bannersSuperview.layoutIfNeeded()
})
} else {
println("Cannot show iAd when bannerView is nil")
}
}
}
func hideiAds() {
if self.showingiAd {
self.showingiAd = false
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
if let bannerView = delegate.bannerView {
if bannerView.superview == self.view {
bannerView.removeFromSuperview()
}
}
}
}
I then check in my viewWillAppear: and viewDidDisappear: methods if an iAds is/should be displayed and calling showiAds(false) and hideiAds() as required.
No matter what I do, I don't seem to be able to get it to work. A couple of other things I've tried but scrapped the code for:
Adding the iAd in the UITabBarController, which then alerts the UITableViewControllers that the iAd was shown/hidden. Modifying the content/scroll indicator insets did not work well, and was ofter reset by the UITableViewController to fit above/below the navigation/tab bar.
(as above) setting the content/scroll indicator insets myself, but I could not get it consistent without attempting to emulate (using (top|bottom)LayoutGuide) in viewDidLayoutSubviews, but this seems very costly?
I did, at one point, have it working by adding the ADBannerView to some view from within the UITableViewController, but it would crash on iOS 7 (something about tableView must call super -layoutSubviews)
EDIT
I have created a UIViewController subclass with the intent of using it to house UITableViewControllers via a Container View. Here is what I have so far, followed by a couple of issues:
class AdvertContainerViewController: UIViewController {
var tableViewController: UITableViewController?
var showingiAd = false
var bannerBottomConstraint: NSLayoutConstraint?
private var bannerTopOffset: CGFloat {
get {
var offset: CGFloat = 0
if let tabBar = self.tabBarController?.tabBar {
offset -= CGRectGetHeight(tabBar.frame)
}
if let bannerView = AppDelegate.instance.bannerView {
let bannerViewHeight = bannerView.frame.size.height
offset -= bannerViewHeight
}
return offset
}
}
override func viewDidLoad() {
super.viewDidLoad()
if self.childViewControllers.count > 0 {
if let tableViewController = self.childViewControllers[0] as? UITableViewController {
self.tableViewController = tableViewController
tableViewController.automaticallyAdjustsScrollViewInsets = false
self.navigationItem.title = tableViewController.navigationItem.title
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if AppDelegate.instance.shouldShowBannerView {
self.showiAds(false)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let delegate = AppDelegate.instance
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showiAds", name: "BannerViewDidLoadAd", object: delegate)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "hideiAds", name: "RemoveBannerAds", object: delegate)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
if self.showingiAd {
self.hideiAds()
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
println("View did layout subviews")
if self.showingiAd {
if let bannerView = AppDelegate.instance.bannerView {
let bannerViewHeight = CGRectGetHeight(bannerView.frame)
if let bottomConstraint = self.bannerBottomConstraint {
let bannerTopOffset = self.bottomLayoutGuide.length + bannerViewHeight
if bottomConstraint.constant != bannerTopOffset {
println("Setting banner top offset to \(bannerTopOffset)")
bottomConstraint.constant = -bannerTopOffset
bannerView.superview?.setNeedsUpdateConstraints()
bannerView.superview?.updateConstraintsIfNeeded()
}
}
println("Bottom layout guide is \(self.bottomLayoutGuide.length)")
let insets = UIEdgeInsetsMake(self.topLayoutGuide.length, 0, self.bottomLayoutGuide.length + bannerViewHeight, 0)
self.updateTableViewInsetsIfRequired(insets)
}
}
}
private func updateTableViewInsetsIfRequired(insets: UIEdgeInsets) {
if let tableView = self.tableViewController?.tableView {
if !UIEdgeInsetsEqualToEdgeInsets(tableView.contentInset, insets) {
println("Updating content insets to \(insets.top), \(insets.bottom)")
tableView.contentInset = insets
}
if !UIEdgeInsetsEqualToEdgeInsets(tableView.scrollIndicatorInsets, insets) {
println("Updating scroll insets to \(insets.top), \(insets.bottom)")
tableView.scrollIndicatorInsets = insets
}
}
}
func showiAds() {
self.showiAds(true)
// self.showiAds(false)
}
func showiAds(animated: Bool) {
if !self.showingiAd {
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
if let bannerView = delegate.bannerView {
println("Showing iAd")
self.showingiAd = true
if (bannerView.superview != self.view) {
bannerView.removeFromSuperview()
}
let bannersSuperview = self.view.superview!
// Added the view and the left/right constraints allow for the proper height
// to be returned when bannerView.frame.size.height is called (iOS 7 fix mainly)
bannersSuperview.addSubview(bannerView)
bannersSuperview.addConstraints([
NSLayoutConstraint(item: bannerView, attribute: .Left, relatedBy: .Equal, toItem: bannersSuperview, attribute: .Left, multiplier: 1, constant: 0),
NSLayoutConstraint(item: bannerView, attribute: .Right, relatedBy: .Equal, toItem: bannersSuperview, attribute: .Right, multiplier: 1, constant: 0),
])
bannersSuperview.layoutIfNeeded()
let bannerBottomConstraint = NSLayoutConstraint(item: bannerView, attribute: .Top, relatedBy: .Equal, toItem: bannersSuperview, attribute: .Bottom, multiplier: 1, constant: 0)
self.bannerBottomConstraint = bannerBottomConstraint
bannersSuperview.addConstraint(bannerBottomConstraint)
bannersSuperview.layoutSubviews()
bannersSuperview.layoutIfNeeded()
let topInset = self.navigationController?.navigationBar.frame.size.height ?? 0
let insets = UIEdgeInsetsMake(topInset, 0, -self.bannerTopOffset, 0)
// Previously, this values was the height of the banner view, so that it starts off screen.
// Setting this to 0 and then doing an animation makes it slide in from below
bannerBottomConstraint.constant = self.bannerTopOffset
bannersSuperview.setNeedsUpdateConstraints()
UIView.animateWithDuration(animated ? 0.5 : 0, animations: { () -> Void in
// Calling layoutIfNeeded here will animate the layout constraint cosntant change made above
self.updateTableViewInsetsIfRequired(insets)
bannersSuperview.layoutIfNeeded()
})
} else {
println("Cannot show iAd when bannerView is nil")
}
}
}
func hideiAds() {
if self.showingiAd {
self.showingiAd = false
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
if let bannerView = delegate.bannerView {
if bannerView.superview == self.view {
bannerView.removeFromSuperview()
}
}
}
}
}
Issues so far:
Using self.view as the superview causes a crash on rotate Auto Layout still required after sending -viewDidLayoutSubviews to the view controller. Gathered.AdvertContainerViewController's implementation needs to send -layoutSubviews to the view to invoke auto layout.
I'm not calculating the content insets correctly; when the iAd is shown, the top jumps up slightly and the bottom in below the top of the banner
The table view doesn't show the scroll indicators. This seems to be a known issue but I cannot find a solution
At the request of Leo Natan I have create a repo on GitHub that I will update with any attempts I make, and explain issues here. Currently, the issues are as follows:
First Tab:
Top of table moves down when iAd is shown (iOS 8)
Table cannot be scrolled (iOS 7)
Top of table view jumps when iAd shows (iOS 7)
Rotation often breaks the offset of the iAd, hiding it behind the tab bar (iOS 7 and 8)
Second Tab:
There are no scroll bars (iOS 7 and 8)
Scroll inset it not set (iOS 7)
Rotation often breaks the offset of the iAd, hiding it behind the tab bar (iOS 7 and 8)
The best solution is to use view controller containment. Use a view controller subclass that will house both the ad view and the table view controller's view, and add the table view controller as a child of the container view controller. This should take care of content insets correctly. On each layout of the container controller's view, position the table controller view hierarchy correctly after positioning the ad view. If you wish to hide the ad view, simply hide or remove it from the container hierarchy, and extend the table controller's view hierarchy fully. When working with hierarchies, remember to always use the table controller's view and not the tableView directly.
My answer was adapted into the following GitHub repo:
https://github.com/JosephDuffy/iAdContainer
The best that is that you download the AD suite from Apple site, there are tabbar controller and navigation controller containment example.
Apple provides you an abstract view controller that can handle by itself the ADBanner flow without interrupting its presentation, maximizing the showing time.
You can use this https://developer.apple.com/library/ios/samplecode/iAdSuite/Introduction/Intro.html apple sample and modified it according to your needs. Such as bool variable to take care of when iAds is shown or not.
There in code you can see BannerViewController class that contains all the logic. You can also write ADmob code there to use.

Resources