OGeek|极客世界-中国程序员成长平台

标题: ios - 使用自动布局在 Storyboard 上实现 ADBannerView [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 08:31
标题: ios - 使用自动布局在 Storyboard 上实现 ADBannerView

我有 Xcode 6.3.2,但在 Storyboard 上实现 ADBannerView 时遇到问题。 Xcode 一直显示警告:

Frame for "Banner View" will be different at run time.

我添加了 3 个约束,您可以在下面看到它们。

所有约束 All of constraints 水平居中 Center horizontally 底部到底部布局指南 = 0 Bottom constraint 前导空格 = 0 enter image description here

如何正确实现banner?

我不能使用“self.canDisplayBannerAds = true”,因为我还使用“bannerViewDidLoadAd”和“didFailToReceiveAdWithError”来调整内容大小,还使用“bannerViewActionShouldBegin”和“bannerViewActionDidFinish”来暂停并重新启动应用程序事件。



Best Answer-推荐答案


解决了!

要在纵向和横向中使用 Auto Layout 和 Size Classes 但不使用 canDisplayBannerAds 添加 iAd 横幅,首先声明横幅 var bannerView: ADBannerView!

使用它来设置委托(delegate)并添加横幅以查看:

func loadAds() {
    bannerView = ADBannerView(adType: ADAdType.Banner)
    bannerView.hidden = true
    bannerView.delegate = self
    self.view.addSubview(bannerView)
}

使用以下代码让横幅随屏幕旋转并在 iAd 加载时调整屏幕内容 contentView 的大小(bottomConstraint 是从 contentView 到底部的约束):

override func viewDidLayoutSubviews() {
    self.layoutAnimated(UIView.areAnimationsEnabled())
}

func layoutAnimated(animated: Bool) {
    var contentFrame = self.view.bounds

    var sizeForBanner = bannerView.sizeThatFits(contentFrame.size)

    var bannerFrame = bannerView.frame
    if self.bannerView.bannerLoaded {

        contentFrame.size.height -= sizeForBanner.height
        bannerFrame.origin.y = contentFrame.size.height
        bannerFrame.size.height = sizeForBanner.height
        bannerFrame.size.width = sizeForBanner.width

        let verticalBottomConstraint = self.bottomConstraint
        verticalBottomConstraint.constant = sizeForBanner.height
        self.view.layoutSubviews()
        bannerView.hidden = false
    } else {
        bannerFrame.origin.y = contentFrame.size.height
        bannerView.hidden = true
        let verticalBottomConstraint = self.bottomConstraint
        verticalBottomConstraint.constant = 0
    }
    UIView.animateWithDuration(animated ? 0.25 : 0.0, animations: {
        self.contentView.layoutIfNeeded()
        self.bannerView.frame = bannerFrame
    })
}

在这里调用上面的代码来在加载或加载 iAd 失败时显示和隐藏横幅

func bannerViewDidLoadAd(banner: ADBannerView!) {
    self.layoutAnimated(true)
}

func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
    self.layoutAnimated(true)
}

现在您可以使用 bannerViewActionShouldBeginbannerViewActionDidFinish 来暂停和启动您的应用事件。

关于ios - 使用自动布局在 Storyboard 上实现 ADBannerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31077025/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4