uicolor initwithCoder提取物颜色名称
我正在尝试通过浏览Uicolor构造方法向iOS添加主题支持的形式。当一个控件使用“命名颜色”(手动添加到资产目录)时,我的故事板的情况遇到了麻烦。打印堆栈跟踪,我可以看到它到达 uicolor(命名:....)
我正在使用的构造器,它调用 uicolor initwithCoder
。我认为,如果我可以改用它并提取故事板中输入的“名称”,那将解决我的问题。 (我知道这个值将在另一个构造函数中传递,但是我需要看看编码器构造函数是否可以从编码器构造函数,长篇小说),
我正在努力理解如何从 nscoder中获取该值
。我找不到有关其基础类型的 uinibdecoder
的任何信息,调试器没有显示任何有用的信息,我不知道该对象使用的键/类型,因此我无法称呼<<<代码> coder.decode ... 函数,我在网上找不到有关如何打印所有键/类型的任何东西。
我目前拥有的代码是类似的:
extension UIColor {
private static let originalCoderSelector = #selector(UIColor.init(coder:))
private static let swizzledCoderSelector = #selector(theme_color(withCoder:))
class func swizzleNamedColorInitToAddTheme() {
guard let originalCoderMethod = class_getInstanceMethod(self, originalCoderSelector),
let swizzledCoderMethod = class_getInstanceMethod(self, swizzledCoderSelector) else {
os_log("Unable to find UIColor methods to swizzle", log: .default, type: .error)
return
}
method_exchangeImplementations(originalCoderMethod, swizzledCoderMethod);
}
@objc func theme_color(withCoder coder: NSCoder) -> UIColor? {
print("coder being called")
print("coder test: \( coder.decodeObject(forKey: "backgroundColor") ) ")
print("coder test: \( coder.decodeObject(forKey: "color") ) ")
print("coder test: \( coder.decodeObject(forKey: "name") ) ")
print("coder test: \( coder.decodeObject(forKey: "namedColor") ) ")
print("coder test: \( coder.decodePropertyList(forKey: "backgroundColor") ) ")
print("coder test: \( coder.decodePropertyList(forKey: "color") ) ")
print("coder test: \( coder.decodePropertyList(forKey: "name") ) ")
print("coder test: \( coder.decodePropertyList(forKey: "namedColor") ) ")
return nil
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在获得编码密钥
,我们可以通过swizzling
nskeyedunarchiver.decodeobject (
forkey 对于我在资产目录中添加的颜色:
从列表中并使用一些常识,
uidyynamicCataLogname
似乎是您想要的关键。请注意,这对基本颜色不起作用,例如
Systemred
或系统颜色,例如SystemBackground
。对于后者,您应该使用键uisystemColorname
(您可以通过编码和解码.Systembackground
)找到此问题。对于前者,仍不清楚使用什么密钥来编码它。通过编码和解码.systemyellow
,我们看到了与.Systembackground
的键,但是使用uisystemcolorname
似乎不起作用。笔尖的编码可能不同...Using the technique in this answer, we can get the coding keys by swizzling
NSKeyedUnarchiver.decodeObject(forKey:)
:Then, you can encode and decode a color to see what keys are decoded:
On iOS 15.0, this prints for a color I added in the asset catalog:
From the list and using some common sense,
UIDynamicCatalogName
seems to be the key that you are looking for.Note that this won't work for base colours like
systemRed
, or system colours likesystemBackground
. For the latter, you should use the keyUISystemColorName
(you can find this by encoding and decoding.systembackground
). For the former, it is still unclear what key is used to encode it. By encoding and decoding.systemYellow
, we see about the same keys as.systembackground
, but usingUISystemColorName
doesn't seem to work. The nib is probably encoded differently...