ixa*_*any 7 storyboard nsview nsviewcontroller segue swift
我想实现一个非常简单的任务 - ViewController通过按下按钮来更改容器视图:
在我的示例中,ViewController1使用Interface Builder 将其嵌入到Container视图中.通过按下按钮ViewController2我想将视图更改为第二个ViewController.
我很困惑,因为容器视图本身似乎是一个NSView如果我创建一个Outlet,据我所知NSView不能包含VC.真的很感谢你的帮助!
小智 9
请注意,要使其工作,您必须向视图控制器添加故事板标识符,这可以转到故事板,然后在右侧窗格中选择Identity Inspector,然后Storyboard ID在Identity子类别中输入.
然后这个实现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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
也许这是一个迟到的答案,但无论如何我都会发布我的解决方案。希望它可以帮助某人。
我在 ContainerView 中嵌入了 NSTabViewController。然后,为了看不到顶部的标签,我这样做了:
转到故事板中的 NSTabViewController
在属性检查器中将样式更改为未指定
然后点击 Tab Bar View Controller 中的 TabView,将样式设置为“tabless”:
在此之后,您需要:
您可以通过在覆盖准备转场功能时存储对 tabViewController 的引用来实现此目的。这是我的代码:
首先将属性添加到 mainViewController
private weak var tabViewController: NSTabViewController?
Run Code Online (Sandbox Code Playgroud)
然后覆盖此函数并保留对 tabViewController 的引用:
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
guard let tabViewController = segue.destinationController
as? NSTabViewController else { return }
**self.tabViewController = tabViewController as? NSTabViewController**
}
Run Code Online (Sandbox Code Playgroud)
在此之后,您将拥有对 tabViewController 的所有设置的引用。接下来(最后)你要做的就是为按钮做一个动作,以便移动到第一个(或第二个)视图控制器,如下所示:
@IBAction func changeToSecondTab(_ sender: Any) {
self.tabViewController?.selectedTabViewItemIndex = 0 // or 1 for second VC
}
Run Code Online (Sandbox Code Playgroud)
祝一切顺利!
| 归档时间: |
|
| 查看次数: |
4211 次 |
| 最近记录: |