2017-04-15 45 views
0

我想在運行時用另一個視圖(及其ViewController)替換一個視圖。現在,當我這樣做時,舊視圖會從窗口中消失,但是新視圖不會出現,並且窗口變爲其原始寬度的兩倍。 如果我切換到全屏模式,我可以在應用程序窗口的左下角看到新的View非常小。可可窗口在替換視圖時的大小加倍

有沒有人知道爲什麼會發生這種情況?我幾個小時都在嘗試所有的事情,但我似乎無法找到發生這種情況的原因。

更換視圖(以及它的ViewController)我使用下面的代碼:

func exchangeDiashowViewController(for newDiashowViewController: NSViewController) { 
    if let oldDiashowViewControllerAsStateObserver = self.diashowViewController as? DiashowStateObserver { 
     DiashowManager.sharedInstance.remove(stateObserver: oldDiashowViewControllerAsStateObserver) 
    } 
    if let oldDiashowViewControllerAsSpeedObserver = self.diashowViewController as? DiashowSpeedObserver { 
     DiashowManager.sharedInstance.remove(speedObserver: oldDiashowViewControllerAsSpeedObserver) 
    } 

    if let newDiashowViewControllerAsStateObserver = newDiashowViewController as? DiashowStateObserver { 
     DiashowManager.sharedInstance.add(stateObserver: newDiashowViewControllerAsStateObserver) 
    } 
    if let newDiashowViewControllerAsSpeedObserver = newDiashowViewController as? DiashowSpeedObserver { 
     DiashowManager.sharedInstance.add(speedObserver: newDiashowViewControllerAsSpeedObserver) 
    } 

    self.view.replaceSubview(self.diashowViewController.view, with: newDiashowViewController.view) 
    self.diashowViewController.removeFromParentViewController() 
    self.addChildViewController(newDiashowViewController) 

    self.diashowViewController = newDiashowViewController 

    let centerHorizontallyConstraint = NSLayoutConstraint(item: self.diashowViewController.view, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0.0) 
    let centerVerticallyConstraint = NSLayoutConstraint(item: self.diashowViewController.view, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.0, constant: 0.0) 
    let widthConstraint = NSLayoutConstraint(item: self.diashowViewController.view, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: 0.0) 
    let heightConstraint = NSLayoutConstraint(item: self.diashowViewController.view, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1.0, constant: 0.0) 

    self.view.addConstraints([centerHorizontallyConstraint, centerVerticallyConstraint, widthConstraint, heightConstraint]) 
} 

我真的希望有人有一個想法。提前感謝!

回答

0

看來self.view.replaceSubview()是問題所在。

我把一切都用

self.diashowViewController.view.removeFromSuperview() 
self.view.addSubview(newDiashowViewController.view) 

,而不是工作。

相關問題