2016-07-05 70 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

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