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

Posted

技术标签:

【中文标题】如何以编程方式向 UIStackView 添加安全区域布局?【英文标题】:How to add safe area layout to UIStackView programmatically? 【发布时间】:2018-07-02 21:56:34 【问题描述】:

我想知道是否有一种聪明的方法可以以编程方式将安全区域布局添加到 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。

目前它看起来像这样。我需要它在安全区域的上方。

【问题讨论】:

【参考方案1】:

不确定是否是最好的方法,但是当我遇到类似情况时,我就是以编程方式进行的:

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);

【讨论】:

以上是关于如何以编程方式向 UIStackView 添加安全区域布局?的主要内容,如果未能解决你的问题,请参考以下文章

如何向放置在 UIStackView 中的以编程方式创建的 UIButton 添加约束

如何以编程方式向 xib 添加约束

如何以编程方式将笔尖添加到 UIStackView

如何以编程方式将 UIImageView 添加到 UIStackView(故事板)

以编程方式填充 UIStackView

以编程方式在 UIStackView 中添加视图