Search code examples
iosswiftautolayoutiadnslayoutconstraint

Autolayout constraint with swift only applied after tap


I am showing an iAD banner like this:

override func viewDidLoad() {
  ...
  initializeBannerAd()
}

func initializeBannerAd() {
  let banner = ADBannerView(adType: ADAdType.Banner)
  banner.frame = CGRectMake(0,-100, self.view.frame.width, 100)
  banner.delegate = self
  banner.hidden = true
  self.view.addSubview(banner)
}

func bannerViewDidLoadAd(banner: ADBannerView!) {
  banner.hidden = false
  banner.frame = CGRectMake(0, self.view.frame.size.height-100, self.view.frame.width, 100)

  banner.setTranslatesAutoresizingMaskIntoConstraints(false)
  let viewsDictionary = ["banner":banner]
  self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[banner]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary))
  self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[banner]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary))
  self.view.layoutIfNeeded()
}

my problem:

  • The first banner loads perfectly and sits snug at the bottom of the screen
  • Whenever the banner updates, it jumps up und stays there until i tap anywhere on the view, then it moves back to the bottom

how can i fix this? why is the constraint applied only after i tap?


Solution

  • The simplest way for you to add an ADBanner at the bottom of a single UIViewController is setting it's property var canDisplayBannerAds: Bool to true. This will trigger an automatic banner presentation without the need to instantiate and add the banner yourself.

    With regard to your code, the first time you see the banner, the auto layout constraints you add in bannerViewDidLoadAd are not yet added. Then they will be added again and again every time a new banner is loaded. You'd better add the constraints in viewDidLoadonce and for all (in case this is the way you intend to present the banner). Since ADBannerView has intrinsic content size defined, you do not need to force the banner size in code. Just add the auto layout rules.

    In case you need an example, here you can find one that I did some time ago for similar questions. In the example I use an ADBannerView singleton and present it at the bottom or top of a viewController's view.

    Hope it can help.