“隐藏"vs #keyPath(UIView.isHidden) [英] "hidden" vs #keyPath(UIView.isHidden)

查看:18
本文介绍了“隐藏"vs #keyPath(UIView.isHidden)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

KVO 观察者不起作用,但 "hidden" 起作用.

KVO observer with #keyPath(UIView.isHidden) does not work, but "hidden" works.

很奇怪.是错误还是功能?

Very strange. Is it bug or feature?

child.addObserver(self, forKeyPath: "hidden", options: [.initial,.new], context: nil);

override func observeValue(forKeyPath keyPath: String?, of object: Any?, .change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if let view = object as? UIView, view.superview === self && keyPath == "hidden" {
        print("*");
    }
}

推荐答案

是错误还是功能?

Is it bug or feature?

假设这是一个已知的事实.重命名"意味着 Swift 假装 Objective-C Bool 属性的名称以 is... 开头,即使它不是.但是#keyPath机制在涉及到KVO和属性setter名称时并没有得到备忘录,并且property setter swizzling来实现KVO观察纯粹是一个Objective-C特性,所以你必须使用属性/setter 的真实名称,即Objective-C 名称,以便与Objective-C 进行通信以实现KVO 观察目的.

Let's say it's a known fact. "Renamification" means that Swift pretends that the name of an Objective-C Bool property starts with is... even when it doesn't. But the #keyPath mechanism didn't get the memo when it comes to KVO and property setter names, and property setter swizzling to implement KVO observing is purely an Objective-C feature, so you have to use the real name of the property / setter, i.e. the Objective-C name, so that communication with Objective-C works correctly for KVO observation purposes.

我已经提交了关于它的错误报告(https://bugs.swift.org/浏览/SR-2415),理由是 Swift 可以在这方面表现得更聪明一点,但在 Swift 帮派回应之前,这只是您所知道和处理的事情.

I've filed a bug report on it (https://bugs.swift.org/browse/SR-2415) on the grounds that Swift could behave a little smarter about this, but until the Swift gang respond, it's just something you have know and deal with.

这篇关于“隐藏"vs #keyPath(UIView.isHidden)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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