swift - 导航到同一窗口内的不同 View Controller

标签 swift macos cocoa nsviewcontroller

我在 Xcode 7.2.1 中创建了一个 OS X Cocoa 应用程序。我为 Main.storyboard 上的默认 View Controller 指定了 Storyboard ID“view1”。我添加了另一个 View Controller ,并为其指定了 Storyboard ID“view2”。我向“view1”添加了一个按钮,并将操作链接到 ViewController.swift 并添加了以下代码:

@IBAction func view1Button(sender: AnyObject) {

    for v in view.subviews {
        v.removeFromSuperview()
    }

    let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
    let sourceViewController = mainStoryboard.instantiateControllerWithIdentifier("view2")
    self.view.addSubview(sourceViewController.view)
}

当我按下“view1”上的按钮时,一切都会按预期进行。 “view1”被关闭,“view2”出现在同一窗口中。

在“view2”上,我做了同样的事情。添加了一个按钮并将操作链接到 ViewController2.swift 并添加了以下代码:

@IBAction func view2Button(sender: AnyObject) {

    for v in view.subviews {
        v.removeFromSuperview()
    }

    let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
    let sourceViewController = mainStoryboard.instantiateControllerWithIdentifier("view1")
    self.view.addSubview(sourceViewController.view)
}

它没有按预期工作。当我单击“view2”上的按钮时,应用程序崩溃,并收到以下错误:“线程 1:EXC_BAD_ACCESS(代码=1,地址=...)。我不明白为什么这不能按预期工作?

最佳答案

我怀疑崩溃的原因是没有对 sourceViewController (您在 view2Button(_:) 中实例化)的强引用。您将其 View 添加为 subview ,这将 View 保留在内存中,但是一旦操作方法返回,将不会对 View Controller 进行强引用,因此当从按钮发送操作消息时,没有 View Controller 可以接收它。

从这段代码的细节中退一步,我建议做一些研究——你试图实现的在 OS X 的 Cocoa 编程中被称为“ View 交换”;在 iOS 中它是“ View Controller 包含”。如果有一个父 View Controller 来进行交换,通常效果会更好。如果您手头有《Cocoa Programming for OS X 5th Edition》,请查看第 31 章。但是如果您没有,您也可以查看 sample code for that chapter。 。尽管如此,我还是建议您看看这本书(免责声明:我是这本书的合著者)。

关于swift - 导航到同一窗口内的不同 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36051445/

相关文章:

arrays - 如何获取对数组中对象的引用

macos - 如何 SFTP 到 Amazon EC2 Ubuntu t1.micro 实例?

swift - 以编程方式使用自动布局在 UIVIew 中将 UITextField 设置为中心

swift - 具有 AES128 CTR 模式的 CryptoSwift - 错误计数器增量?

macos - 在 OS X 上,如何将我的 shell 从 fish 改回 bash?

python - 在 mac os 上使用 django 安装 mysql

objective-c - 在 Cocoa 中查找文件的最后访问日期

Objective-C::使用方法来改变对象

cocoa - 如何使单个 NSView 中显示的所有内容变暗?

swift - 从异步函数为变量赋值