如何以编程方式向UIStackView添加安全区域布局?

时间:2018-07-02 21:56:35

标签: swift admob uistackview safearealayoutguide

我想知道是否存在一种聪明的方法来以编程方式向UIStackView添加安全区域布局。目前这是我的设置:

// AppDelegate.didFinishLaunchingWithActions
let rvc = window?.rootViewController
adViewController = AdViewController(contentViewController: rvc!)
window?.rootViewController = adViewController
window?.makeKeyAndVisible()

// AdViewController.swift
private var bannerView = GADBannerView(adSize: kGADAdSizeBanner)
let contentViewController: UIViewController

init(contentViewController: UIViewController) {
    self.contentViewController = contentViewController
    super.init(nibName: nil,bundle: nil)
}

override func loadView() {
    let stackView = UIStackView(arrangedSubviews: [contentViewController.view, bannerView])
    stackView.distribution = .fill
    stackView.axis = .vertical
    self.addChildViewController(contentViewController)
    contentViewController.didMove(toParentViewController: self)
    view = stackView
    self.stackView = stackView
}

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
    setupAdbanner()
    let adsDisabled = MKStoreKit.shared().isProductPurchased(AppConfig.kRemoveAdsID)
    self.setAdvertisingViewHidden(adsDisabled, animated: false)

    NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
}

private func setupAdbanner() {
    bannerView.delegate = self
    bannerView.backgroundColor = .clear
    bannerView.rootViewController = self
    bannerView.adUnitID = AppConfig.kAdUnitIDBanner
}

我尝试以Use Safe Area Layout programmatically的方式实现它。但似乎这种方式无法在UIStackViews中使用。

当前看起来像这样。我需要它在安全区域内。 AdMob display

1 个答案:

答案 0 :(得分:0)

不确定是否最好的方法,但是当我遇到类似情况时,我是通过编程方式完成的:

CGFloat yPos = [UIScreen mainScreen].bounds.size.height;
CGFloat width = [UIScreen mainScreen].bounds.size.width;
if (@available(iOS 11.0, *)) {
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    CGFloat bottomPadding = window.safeAreaInsets.bottom;
    CGFloat topPadding = window.safeAreaInsets.top;
    CGFloat leftPadding = window.safeAreaInsets.left;
    CGFloat rightPadding = window.safeAreaInsets.right;
    yPos -= (bottomPadding + topPadding);
    width -= (leftPadding + rightPadding);
}