微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)
        }

    }
}

原文地址:https://www.jb51.cc/swift/318710.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐