在iOS库类的现有属性上添加属性观察器 [英] Add a property observer on an existing property in an iOS library class

查看:95
本文介绍了在iOS库类的现有属性上添加属性观察器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的SpriteKit游戏中,我想在我的Sprite的SKPhysicsBodyfieldBitMask属性上添加一个属性观察器.我想在fieldBitMask属性更改时得到通知,以便我可以采取一些措施.

In my SpriteKit game, I want to add a property observer on the fieldBitMask property for the SKPhysicsBody of my sprites. I want to be informed when the fieldBitMask property changes so that I can take some action.

我覆盖了SKPhysicsBody,但是当我尝试将覆盖的类分配给像普通SKPhysicsBody对象这样的sprite节点时,出现了很多错误.我还考虑过为SKPhysicsBody进行扩展,但是Apple文档说:扩展可以为类型添加新功能,但不能覆盖现有功能."因此,似乎无法以这种方式覆盖fieldBitMask属性以使其成为属性观察器.

I overrode SKPhysicsBody but when I tried assigning the overridden class to a sprite node like a normal SKPhysicsBody object I got a bunch of errors. I also thought about making an extension for SKPhysicsBody, but Apple documentation says, "Extensions can add new functionality to a type, but they cannot override existing functionality." So it would seem that I can't override the fieldBitMask property this way to make it a property observer.

我知道如何在我创建的新的自定义类中创建属性观察器.但是,将属性观察器添加到Apple库中包含的类的现有属性中的最佳方法是什么?

I know how to create a property observer in a new custom class which I create. But what is the best way to add a property observer to an existing property in a class that is part of the Apple library?

推荐答案

我认为您可以使用实现 observeValue(forKeyPath:of:change:context:)方法.

I think you can use the Key Value Observing. You can add observer to a property changing.
You should implement observeValue(forKeyPath:of:change:context:) method in your observer class.

此处您可以找到Swift示例(键值观察"部分).

Here you can find Swift example ("Key-Value Observing" part).

这篇关于在iOS库类的现有属性上添加属性观察器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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