在添加到UIWindow的视图上使用autolayout

Tom*_*you 5 ios swift

我正在尝试将子视图添加到keyWindow应用程序中,并使用autolayout定位它.但是,autolayout似乎根本不起作用,而设置框架则可以.我想使用以下代码将我的视图对齐infoSc到底部keyWindow:

let infoSc = InfoScreenView()
infoSc.translatesAutoresizingMaskIntoConstraints = false

let keyWindow = UIApplication.sharedApplication().keyWindow!
keyWindow.addSubview(infoSc)
keyWindow.addConstraint(NSLayoutConstraint(item: infoSc, attribute: .Left, relatedBy: .Equal, toItem: keyWindow, attribute: .Left, multiplier: 1, constant: 0))
keyWindow.addConstraint(NSLayoutConstraint(item: infoSc, attribute: .Right, relatedBy: .Equal, toItem: keyWindow, attribute: .Right, multiplier: 1, constant: 0))
keyWindow.addConstraint(NSLayoutConstraint(item: infoSc, attribute: .Bottom, relatedBy: .Equal, toItem: keyWindow, attribute: .Bottom, multiplier: 1, constant: 0))
infoSc.addConstraint(NSLayoutConstraint(item: infoSc, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100))
Run Code Online (Sandbox Code Playgroud)

但是,似乎有一个CGRectZero使用此方法的框架.任何想法如何使这项工作?理想情况下,我也想将它与内部的东西对齐self.view,但是会抛出一个self.view不在视图层次结构中的错误keyWindow.

Dav*_* S. 6

如果需要在整个窗口上绘制,请执行以下代码(在此示例中,我在中AppDelegate,因此window是该AppDelegate.window属性)。

func tryToDrawOnTheWindow()
{
    if let window = window, view = window.rootViewController?.view
    {
            print("I have a root view")

            let infoSc = InfoScreenView(frame: view.frame)
            let count = view.subviews.count
            view.insertSubview(infoSc, atIndex: count)
            infoSc.translatesAutoresizingMaskIntoConstraints = false
            let height = NSLayoutConstraint(item: infoSc, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1, constant: 0)
            let width = NSLayoutConstraint(item: infoSc, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0)
            let offset = NSLayoutConstraint(item: infoSc, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)
            print([height, width, offset])
            view.addConstraints([height, width, offset])
    }
    else
    {
        print("No root view on which to draw")
    }
}
Run Code Online (Sandbox Code Playgroud)

这将使您可以在视图层次结构中的任何内容之上进行绘制。在我的测试应用程序中,我添加了一个文本字段和一个蓝色矩形,并且覆盖层为橙色,不透明度为40%。请记住,在这种情况下,默认情况下,叠加视图将消耗所有抽头。