swift 键值对
In this article, we will learn key-value observing(KVO) in Swift and see its implementation on a simple Xcode Playgrounds example.
在本文中,我们将学习Swift中的键值观察(KVO),并在一个简单的Xcode Playgrounds示例中看到其实现。
In short, key-value observation allows us to observe and react to a property’s changes. It’s especially useful when we want to instantly display a change from our Model
layer on a UIView
subclass.
简而言之,键值观察使我们能够观察和响应属性的变化。 当我们想立即在UIView
子类上显示来自Model
层的更改时,它特别有用。
The source code of the project is available at the bottom of the article.
该项目的源代码位于文章底部。
开始吧 (Let’s Start)
Consider the following Counter
class:
考虑以下Counter
类:
To make the Counter
eligible for the key-value observation, we must inherit from the NSObject
, and mark the property we want to observe as @objc dynamic
. In our case, that property is value
.
为了使Counter
符合键值观察的条件,我们必须继承NSObject
,并将要观察的属性标记为@objc dynamic
。 在我们的例子中,该属性就是value
。
Our model is ready, let’s now create a UIView
:
我们的模型已经准备就绪,现在让我们创建一个UIView
:
The CounterView
displays a UILabel
in the center and has an “Append” UIButton
at the top. We want to increment the value of the Counter
on button tap and bind it to the label.
CounterView
在CounterView
显示一个UILabel
,在顶部有一个“追加” UIButton
。 我们想增加“点击按钮时Counter
的值并将其绑定到标签。
We can see that we add a counter
(marked as an Objective-C member) and an observation
properties. Inside the initializer, we observe changes in the Counter
’s value property as follows:
我们可以看到我们添加了一个counter
(标记为Objective-C成员)和observation
属性。 在初始化程序内部,我们观察到Counter
的value属性的变化,如下所示:
As a result, the currentCountLabel
immediately updates as the value changes:
结果, currentCountLabel
随着值的更改而立即更新:
资源资源 (Resources)
The full source code of the project:
项目的完整源代码:
结语 (Wrapping Up)
Interested in more lesser-known features of Swift? Feel free to check out my other relevant articles:
对Swift鲜为人知的功能感兴趣吗? 随时查看我的其他相关文章:
Thanks for reading!
谢谢阅读!
翻译自: https://levelup.gitconnected.com/implement-the-key-value-observation-in-swift-5-e6f24638a26f
swift 键值对