我试图在运行时将一个视图(及其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])
}
我真的希望有人有一个主意。在此先多谢!
最佳答案
看来self.view.replaceSubview()
是问题所在。
我通过使用使一切正常
self.diashowViewController.view.removeFromSuperview()
self.view.addSubview(newDiashowViewController.view)
代替。
关于swift - 更换 View 时, cocoa 窗的尺寸增加了一倍,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43428777/