问题描述
我想实现一个非常简单的任务——通过按下一个按钮来改变容器视图的ViewController
:
I want to achieve a really simple task—changing the ViewController
of a Container View by pressing a button:
在我的示例中,ViewController1
使用 Interface Builder 嵌入到容器视图中.通过按下按钮 ViewController2
,我想将视图更改为第二个 ViewController.
In my example the ViewController1
is embedded into the Container View using Interface Builder. By pressing the Button ViewController2
I want to change the view to the second ViewController.
我很困惑,因为如果我创建一个 Outlet,Container View 本身似乎是一个 NSView
并且据我所知 NSView 不能包含 VC.非常感谢您的帮助!
I’m confused because the Container View itself seems to be a NSView
if I create an Outlet and as far as I know a NSView can’t contain a VC. Really appreciate your help!
推荐答案
请注意,为了使此功能正常工作,您必须将故事板标识符添加到您的视图控制器中,这可以通过转到您的故事板然后在右侧窗格,然后在 Identity
子类别中输入 Storyboard ID
.
Just note that in order for this to work you have to add storyboard identifiers to your view controllers, which can by going to your storyboard then selecting the Identity Inspector in the right hand pane and then entering the Storyboard ID
in the Identity
subcategory.
然后 ViewController
的这个实现将实现你正在寻找的东西.
Then this implementation of ViewController
would achieve what you are looking for.
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:在容器视图/NSView 中的 NSViewController 之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!