从另一个类更改 IBOutlet 的值 [英] Changing the values of an IBOutlet from another class

查看:33
本文介绍了从另一个类更改 IBOutlet 的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个计算器应用程序作为我在 Xcode 中的第一个项目,并且我正在尝试实现按键功能.为了做到这一点,我创建了一个包含所有代码的 Global 类,以便我的 NSWindow 类和我的 NSViewController 类都可以访问它没有错误,因为该应用程序取决于更改 IBOutlet 的文本.然而,问题是它返回一个 意外发现 nil,同时用我目前得到的代码解包一个可选值,我真的不知道我还能怎么做:>

这是我从 Global 类访问 IBOutlet 的方式:viewInstance.configureLabel(newString: newEquationCacheLabel)

这是访问的内容:

@IBOutlet 弱私有 var equationCacheLabel: NSTextField!功能配置标签(新字符串:字符串){equationCacheLabel.stringValue = newString}

然后是我的 ViewController 的一个全局实例(在类之外声明):let viewInstance = ViewController()

先谢谢你!

解决方案

感谢所有帮助过的人,但事实证明它返回 nil 的原因是我正在访问一个 版本.我正在访问我自己的 ViewController 版本,它没有初始化版本的 equationCacheLabel.事实证明,如果我访问了实际显示在应用程序中的 NSViewController,它工作得很好.这是我访问 NSViewController 的方式(请注意,我正在创建一个 OS X/macOS Swift 应用程序,这不适用于 i/tv/watchOS 应用程序或 Objective-C 应用程序):

(NSApplication.shared().keyWindow?.contentViewController as!ViewController)

这将使您能够访问当前显示的 ViewController 以及您需要的任何 IBActions/Outlets.

I'm creating a Calculator app as my first project in Xcode, and I'm trying to implement key pressing functionality. In order to do this, I created a Global class which housed all of the code so that both my NSWindow class and my NSViewController class could access it without errors, since the app hinges on changing the text of an IBOutlet. However the problem is that it returns an unexpectedly found nil while unwrapping an Optional value with the code I've currently got, and I really don't know how else I could go about doing this:

This is how I access the IBOutlet from the Global class: viewInstance.configureLabel(newString: newEquationCacheLabel)

This is what that accesses:

@IBOutlet weak private var equationCacheLabel: NSTextField!

func configureLabel(newString: String) {
    equationCacheLabel.stringValue = newString
}

And then there's a global instance of my ViewController (declared outside of the class): let viewInstance = ViewController()

Thank you in advance!

解决方案

Thank you all who helped, but it turns out that the reason it was returning nil was that I was accessing a nil version. I was accessing my own version of ViewController, which didn't have an initalized version of equationCacheLabel. It turned out that if I accessed the NSViewController actually being displayed in the app, it worked just fine. This is how I accessed that NSViewController (note that I'm creating an OS X/macOS Swift app, this will not work in an i/tv/watchOS app or an Objective-C app):

(NSApplication.shared().keyWindow?.contentViewController as! ViewController)

That will get you access to the ViewController currently being displayed, and any IBActions/Outlets you need.

这篇关于从另一个类更改 IBOutlet 的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆