swift 键值对_在Swift 5中实现键值观察

本文介绍了如何在Swift 5中实现键值观察(Key-Value Observing, KVO),这是一种用于监听对象属性变化的机制。通过学习,你可以掌握在Swift应用中监控特定属性变化的方法。" 78562905,5760609,Python中的grok:高级正则匹配库,"['python', '正则表达式', '数据处理', '库', 'pygrok']
摘要由CSDN通过智能技术生成

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.

CounterViewCounterView显示一个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随着值的更改而立即更新:

Image for post

资源资源 (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 键值对

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值