ios - 在添加到 UIWindow 的 View 上使用自动布局

标签 ios swift

我正在尝试向 keyWindow 添加一个 subview 应用程序的位置,并使用自动布局对其进行定位。但是,自动布局似乎根本不起作用,而设置框架却可以。我想调整我的观点 infoSckeyWindow 的底部使用以下代码:

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

但是,它的框架似乎是 CGRectZero使用这种方法。任何想法如何使这项工作?理想情况下,我还想将它与内部的东西对齐 self.view也是,但这会引发一个错误 self.view不在 keyWindow 的 View 层次中.

最佳答案

如果你需要在整个窗口上绘制,这里是代码来完成它(在这个例子中我在 AppDelegate 中,所以窗口是 AppDelegate.window属性(property))。

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")
    }
}

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

关于ios - 在添加到 UIWindow 的 View 上使用自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38208215/

相关文章:

ios - 为什么我在 Cocos2D 中的 32 位上下文周围有一条黑线?

ios - UIView Controller 高度小于原始高度swift 4

ios - 使用 for 循环在 Swift 中减去两个对象数组还是有更好的方法?

ios - 使用 SDWebImage 时表格 View 滚动滞后

ios - 从框架位置获取 UIView 对象

java - 当手指在屏幕的同一位置时执行事件? libgdx

ios - 存储空间已满时将应用程序数据保存到用户的 iCloud(CloudKit)?

ios - iOS 应用程序中的 Realm 文件大小

swift - 不确定的进度指示器没有动画

ios - swift 将 NSDictionary 分配给全局 NSMUtableDictionary