我正在更改各种事物,例如图层背景颜色,字体颜色等等。当我的用户单击文档窗口中的按钮时,该过程从视图控制器中的IBAction开始(如下所示)。目前这可行,但仅影响我的基于OS X文档的应用程序中的活动窗口。
如果同时打开多个文档窗口,我希望更改会影响所有打开的窗口,而不仅仅是活动窗口。
它仅在当前重新启动应用程序后影响所有窗口。
感谢接受以下答复:
在窗口控制器中添加:
@IBAction func themeButtonClicked(sender: AnyObject) {
var thetag = sender.tag()
NSNotificationCenter.defaultCenter().postNotificationName("updateTheme", object: nil, userInfo: ["tag": thetag])
}
override func windowDidLoad() {
super.windowDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleNotification:", name: "updateTheme", object: nil)
}
func handleNotification(notification:NSNotification){
let userInfo:Dictionary<String,Int!> = notification.userInfo as Dictionary<String,Int!>
let thetag:Int = userInfo["tag"]!
switch thetag {
case 0 :
theCurrentTheme = "white"
Defaults["theme"] = "white"
case 1 :
theCurrentTheme = "cream"
Defaults["theme"] = "cream"
case 2 :
theCurrentTheme = "black"
Defaults["theme"] = "black"
default:
theCurrentTheme = "white"
Defaults["theme"] = "white"
}
}
答案 0 :(得分:1)
我认为,如果您想要对任何打开的文档进行更改,并且触发方不知道打开了哪个或多少文档,您应该发布NSNotification
,并拥有感兴趣的各方听取它(注册)。
因此,除了窗口控制器制定更改作为对其按钮的响应之外&#39; IBAction
,他们也可以注册通知(最终由窗口控制器的另一个实例发布)并执行与按下按钮时完全相同的事情。
ADDENDUM:您应该调用仅从通知处理程序执行更改的实际方法,并且在IBAction
内您应该只发布通知。否则,触发操作的窗口控制器将执行 两次更改 !
...这意味着,您不再需要一个单独的私有方法(只从一个地方调用它),而是可以代替通知处理程序内部更改的逻辑。