2016-07-05 71 views
1

我试图将子视图添加到应用的keyWindow,并使用自动布局进行定位。但是,自动布局似乎不起作用,而设置一个帧却行。我想我的观点infoSc对齐到keyWindow的使用下面的代码底部:在视图中使用自动布局添加到UIWindow

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的视图层次结构中的错误。

+0

显示完整的错误 – anders

回答

1

如果您需要在整个窗口中绘制,这里是代码(在这个例子中,我在AppDelegate,所以窗口是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") 
    } 
} 

这将让您在视图层次结构的顶部绘图。在我的测试应用程序中,我添加了一个文本框和一个蓝色矩形,叠加层为橙色,透明度为40%。请记住,在这种情况下,默认情况下,叠加视图将消耗所有的水龙头。

+0

我使用了窗口,因为我的InfoScreenView必须位于所有视图之上(包括任何导航栏等)。从基本意义上说,它画圆圈来突出显示屏幕上的区域。你的代码可以工作,但会受到导航控制器/标签栏控制器中可能包含的'视图'的限制。 – Tometoyou

+0

好的,更新了答案以反映你正在尝试做的事情。 –