我正在尝试向 keyWindow
添加一个 subview 应用程序的位置,并使用自动布局对其进行定位。但是,自动布局似乎根本不起作用,而设置框架却可以。我想调整我的观点 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))
但是,它的框架似乎是 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/