Xcode-将文本字段绑定到Swift字典的元素 [英] Xcode - Bind textfield to element of a Swift dictionary

查看:109
本文介绍了Xcode-将文本字段绑定到Swift字典的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实通过接口构建器将文本字段绑定到Swift字典值.在文本字段中,将正确的值从字典中提取出来并显示在文本字段中.

I did bind a textfield to a Swift dictionary value via interface builder. In the textfield the correct value is pulled from the dictionary and displayed in the textfield.

当我通过

myDict["Textfield1"] = "New value"

该更改在文本字段中不可见. 当我确实将文本字段的值绑定到类的属性时,对该属性的任何更改都将立即在文本字段中可见. 我想念什么吗?

the change is not visible in the textfield. When I do bind the value of the textfield to a property of a class, any change to this property is instantly visible in the textfield. Am I missing something?

谢谢!

推荐答案

所以基本上,它不会起作用.绑定使用KVO/KVN系统工作,该系统在Obj-C对象更改其值时发出通知.它非常聪明,但是他们没有将其移植到Swift.此外,Swift中的字典是值类型.

So basically, it won't work. Bindings work by using the KVO/KVN system, which sends out notifications when Obj-C objects change their value. It's very clever, but they didn't port it to Swift. To add to that, dictionaries in Swift are value types.

解决方案"是确保您绑定的东西具有KVO.因此,您可以做几件事.首先是创建您自己的类并从NSObject对其进行子类化,然后您将获得KVO. 这是有关操作方法的页面那个.

The "solution" is to make sure the thing you bind to has KVO. So there's a couple of things you can do. The first is to make your own class and subclass it from NSObject, and presto, you get KVO. Here's a page on how to do that.

但是更好的方法是在Swift集合myDict上使用dynamic关键字.这触发了到Obj-C的桥接,因此您获得了KVO.现在,我还没有在Swift字典中使用它,所以我不太确定会发生什么.您可能必须使myDict成为NSDictionary.但这是一个较小的更改,因此绝对可以尝试dynamic

But the better way is to use the dynamic keyword on your Swift collection, myDict. This triggers the bridging into Obj-C, and so you get KVO. Now I haven't used this with a Swift dict, so I'm not totally sure what will happen. You may have to make the myDict a NSDictionary. But it's one minor change, so definitely give dynamic a try!

这篇关于Xcode-将文本字段绑定到Swift字典的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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