gpt4 book ai didi

Swift:在 Container View/NSView 内的 NSViewController 之间切换

转载 作者:行者123 更新时间:2023-11-30 10:53:40 24 4
gpt4 key购买 nike

我想实现一个非常简单的任务 - 通过按下按钮来更改容器 View 的 ViewController:

enter image description here

在我的示例中,ViewController1 使用 Interface Builder 嵌入到容器 View 中。通过按按钮 ViewController2 我想将 View 更改为第二个 ViewController。

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

最佳答案

请注意,为了使其正常工作,您必须将 Storyboard标识符添加到 View Controller 中,方法是转到 Storyboard,然后在右侧 Pane 中选择“身份检查器”,然后输入 Storyboard IDIdentity 子类别中。

然后 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.addChild(vc1)
self.addChild(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:在 Container View/NSView 内的 NSViewController 之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54193224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com