加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift:在Container View / NSView中切换NSViewController

发布时间:2020-12-14 05:40:12 所属栏目:百科 来源:网络整理
导读:我想实现一个非常简单的任务 – 通过按下按钮来更改容器视图的ViewController: 在我的示例中,ViewController1使用Interface Builder嵌入到Container视图中.通过按下Button ViewController2,我想将视图更改为第二个ViewController. 我很困惑,因为如果我创建
我想实现一个非常简单的任务 – 通过按下按钮来更改容器视图的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)
        }

    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读