Xcode - Bind textfield to element of a Swift dictionary

懵懂的女人 提交于 2020-01-06 04:14:07

问题


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.

When I change the value of the element in the dict via

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?

Thanks!


回答1:


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.

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.

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!



来源:https://stackoverflow.com/questions/39624690/xcode-bind-textfield-to-element-of-a-swift-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!