替换视图时,Cocoa窗口的大小翻倍

时间:2017-04-15 17:00:05

标签: swift macos cocoa nsview nslayoutconstraint

我试图在运行时用一个不同的View替换一个View(和它的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])
}

我真的希望有人有个主意。非常感谢提前!

1 个答案:

答案 0 :(得分:0)

似乎问题是self.view.replaceSubview()

我使用

完成了所有工作
self.diashowViewController.view.removeFromSuperview()
self.view.addSubview(newDiashowViewController.view)

代替。