gpt4 book ai didi

xcode - 如何让 NSViewController 与 Swift 中的 NSToolbar 通信?

转载 作者:可可西里 更新时间:2023-11-01 01:40:11 29 4
gpt4 key购买 nike

我正在制作一个简单的 OS X 应用程序,看起来像在 Interface Builder 中:

背景故事

MainViewNSViewController 的子类,工具栏是我用 Interface Builder 构建的简单 NSToolbar。默认情况下,NSToolbar 项目是启用的,但它们没有任何用处,直到 Main Image View 包含一个 NSImage,所以我想要我的 NSViewController (MainView) 以在接收到图像时启用工具栏按钮,并在按下“清除”按钮时禁用它们。

问题

为了实现工具栏操作,我遵循了this answer ,所以现在我有一个 MainView.swift 实现了带有工具栏 IBActions 的 NSViewController(并且它有效),因此我的工具栏可以将操作发送到我的 View 。但是我无法让工具栏从 NSViewController 接收消息,因为它们不在同一个对象中:我的工具栏在 Window 中,我的 MainImageView MainView 的 View 中。

问题

根据我的搜索结果,我应该使用委托(delegate),所以我开始制作一个简单的协议(protocol):

protocol MainToolbarDelegate {
func setButtonsEnabled(to:Bool)
}

但是,在我的 class MainView: NSViewController 中设置 var delegate: MainToolbarDelegate 时,我遇到了同样的问题:我无法指向工具栏,因为它不在同一个对象,并且没有 segue 将一个对象链接到另一个对象。我试过 var delegate: MainToolbarDelegate = self.view.window.toolbar 但 Xcode 返回错误。

那么现在,我的问题是:我错过了什么?那是我第一次使用委托(delegate),所以我可能会做一些完全错误的事情。我是否需要子类化我的 Window 以便我可以使用 segues?

如果我的问题不准确,再次抱歉,我完全迷路了。

最佳答案

使用通知!

假设您想根据在 ViewControler 中执行的操作启用/禁用删除项目按钮。首先,您需要添加一些自定义通知(这是针对 Xcode 8 beta 6 上的 Swift 3,语法和命名可能因您的版本或最终版本而异):

extension Notification.Name {
static let rowSelected = Notification.Name("turnOn")
static let rowDeselected = Notification.Name("turnOff")
}

接下来,您需要为要使用的按钮添加一个 outlet,并在窗口 Controller 中添加观察者和函数来处理操作:

class SummaryWindowController: NSWindowController {

@IBOutlet weak var removeProjectButton: NSToolbarItem!

required init?(coder: NSCoder) {
super.init(coder: coder)
shouldCascadeWindows = true
}

override init(window: NSWindow?) {
super.init(window: window)

}

override func windowDidLoad() {
super.windowDidLoad()

self.removeProjectButton.isEnabled = false

NotificationCenter.default.addObserver(self, selector: #selector(SummaryWindowController.enableRemoveButton(_:)), name: .turnOn, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SummaryWindowController.disableRemoveButton(_:)), name: .turnOff, object: nil)
}

func enableRemoveButton(_ notification: Notification) {
self.removeProjectButton.isEnabled = true
}

func disableRemoveButton(_ notification: Notification) {
self.removeProjectButton.isEnabled = false
}
}

然后您需要一个 View Controller 来发送操作。在这种情况下,它将是 View 中的两个按钮:

class SummaryViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {

override func viewDidLoad() {
super.viewDidLoad()

}

@IBAction func onButtonTapped(sender: NSButton) {
NotificationCenter.default.post(Notification(name: .turnOn))
}

@IBAction func offButtonTapped(sender: NSButton) {
NotificationCenter.default.post(Notification(name: .turnOff))
}
}

关于xcode - 如何让 NSViewController 与 Swift 中的 NSToolbar 通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30440206/

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