如果您的拆分视图项目具有自定义控制器,您可以通过NSSplitViewController.splitViewItemForViewController(viewController: NSViewController)
.
我会为每个视图控制器声明一个协议:
protocol MainSplitViewControllerProtocol {
var thisSplitItemController: ThisSplitViewItemControllerProtocol? {get set}
var thatSplitItemController: ThatSplitViewItemControllerProtocol? {get set}
}
protocol ThisSplitViewItemControllerProtocol {
//any contracts you need here
}
protocol ThatSplitViewItemControllerProtocol {
//any contracts you need here
}
然后我会像这样声明我的具体类:
class MainSplitViewController: NSSplitViewController, MainSplitViewControllerProtocol {
var thisSplitItemController: ThisSplitViewItemControllerProtocol?
var thatSplitItemController: ThatSplitViewItemControllerProtocol?
var thisSplitViewItem: NSSplitViewItem?
var thatSplitViewItem: NSSplitViewItem?
override func viewWillAppear() {
thisSplitViewItem = thisSplitItemController != nil ? self.splitViewItemForViewController(thisSplitItemController as! NSViewController : nil)
thatSplitViewItem = thatSplitItemController != nil ? self.splitViewItemForViewController(thatSplitItemController as! NSViewController : nil)
}
}
class ThisViewController: NSViewController, ThisSplitViewItemControllerProtocol {
var parent: MainSplitViewControllerProtocol?
override func viewdidLoad() {
super.viewDidLoad()
parent = (self.parentViewController as! MainSplitViewControllerProtocol)
parent?.thisSplitItemController = self
}
}
class ThatViewController: NSViewController, ThatSplitViewItemControllerProtocol {
var parent: MainSplitViewControllerProtocol?
override func viewdidLoad() {
super.viewDidLoad()
parent = (self.parentViewController as! MainSplitViewControllerProtocol)
parent?.thatSplitItemController = self
}
}
现在我可以访问拆分视图项,无论它们在父级的 splitViewItems 数组中的索引如何:
extension MainSplitViewController {
func toolbarButtonClick(button: NSButton) {
thisSplitViewItem?.collapsed = !thisSplitViewItem?.collapsed
thatSplitViewItem?.collapsed = !thatSplitViewItem?.collapsed
}
}
通过使用协议,我还解耦了所有视图控制器,因此可以轻松交换视图。如果您需要从另一个 NSSplitViewItem 控制其中一个 NSSplitViewItems(或任何其他属性)的折叠状态,请将相关的 NSSplitViewItem 作为属性添加到您的 NSSplitViewController 协议中。