Swift:在Container View / NSView中切换NSViewController

前端之家收集整理的这篇文章主要介绍了Swift:在Container View / NSView中切换NSViewController前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想实现一个非常简单的任务 – 通过按下按钮来更改容器视图的ViewController:

在我的示例中,ViewController1使用Interface Builder嵌入到Container视图中.通过按下Button ViewController2,我想将视图更改为第二个ViewController.

我很困惑,因为如果我创建一个Outlet,Container View本身似乎是一个NSView,据我所知,NSView不能包含VC.真的很感谢你的帮助!

请注意,要使其工作,您必须将故事板标识符添加到视图控制器,这可以转到故事板,然后在右侧窗格中选择Identity Inspector,然后在Identity子类别中输入Storyboard ID.

然后,ViewController的这个实现将实现您正在寻找的.

import Cocoa

class ViewController: NSViewController {

    // link to the NSView Container
    @IBOutlet weak var container : NSView!

    var vc1 : ViewController1!
    var vc2 : ViewController2!

    var vc1Active : Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Make sure to set your storyboard identiefiers on ViewController1 and ViewController2
        vc1 = NSStoryboard(name: "name",bundle: nil).instantiateController(withIdentifier: "ViewController1") as! ViewController1
        vc2 = NSStoryboard(name: "name",bundle: nil).instantiateController(withIdentifier: "ViewController2") as! ViewController2

        self.addChildViewController(vc1)
        self.addChildViewController(vc2)
        vc1.view.frame = self.container.bounds
        self.container.addSubview(vc1.view)
        vc1Active = true

    }

    // You can link this action to both buttons
    @IBAction func switchViews(sender: NSButton) {

        for sView in self.container.subviews {
            sView.removeFromSuperview()
        }

        if vc1Active == true {

            vc1Active = false
            vc2.view.frame = self.container.bounds
            self.container.addSubview(vc2.view)

        } else {

            vc1Active = true
            vc1.view.frame = self.container.bounds
            self.container.addSubview(vc1.view)
        }

    }
}

猜你在找的Swift相关文章