【发布时间】:2017-03-18 18:34:12
【问题描述】:
我正在尝试在 Swift 中比较不同的颜色。一切都很好,直到我重新构建应用程序。相同的颜色,相同的代码,但它不起作用。
我正在为文本添加背景颜色,并且我有不同的主题。当用户更改主题时,应用程序还应更改该主题的背景颜色。使用该应用程序时一切都很好,但是当我重建项目时,它并没有像应有的那样比较颜色。
这是我正在使用的代码:
for i in 0...noteTextView.attributedText.length-1
{
noteTextView.attributedText.enumerateAttribute(NSBackgroundColorAttributeName, in: NSMakeRange(i,1), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) -> Void in
if let exValue = value as? UIColor
{
if(exValue.isEqualWithConversion(UIColor(hex: 0x2e3f4f))) || (exValue.isEqualWithConversion(UIColor(hex: 0xc0e1ff))) || (exValue.isEqualWithConversion(UIColor(hex: 0x2970ae))) || (exValue.isEqualWithConversion(UIColor(hex: 0xaad5fb)))
{
aRange = NSMakeRange(i, 1)
print("blue")
myValue = styles.blueHighlightColor()
self.noteTextView.textStorage.addAttribute(attributeName, value: myValue, range: aRange)
saveChanges = true
}
else if (exValue.isEqualWithConversion(UIColor(hex: 0xcafd70))) || (exValue.isEqualWithConversion(UIColor(hex: 0xbde970))) || (exValue.isEqualWithConversion(UIColor(hex: 0x568a56))) || (exValue.isEqualWithConversion(UIColor(hex: 0xbde970)))
{
aRange = NSMakeRange(i, 1)
print("green")
myValue = styles.greenHighlightColor()
self.noteTextView.textStorage.addAttribute(attributeName, value: myValue, range: aRange)
saveChanges = true
}
else if (exValue.isEqualWithConversion(UIColor(hex: 0x51445d))) || (exValue.isEqualWithConversion(UIColor(hex: 0xd6affb))) || (exValue.isEqualWithConversion(UIColor(hex: 0x79569b))) || (exValue.isEqualWithConversion(UIColor(hex: 0xd6affb)))
{
aRange = NSMakeRange(i, 1)
print("pink")
myValue = styles.pinkHighlightColor()
self.noteTextView.textStorage.addAttribute(attributeName, value: myValue, range: aRange)
saveChanges = true
}
else if (exValue.isEqualWithConversion(UIColor(hex: 0xffffff))) || (exValue.isEqualWithConversion(UIColor(hex: 0xfbe769))) || (exValue.isEqualWithConversion(UIColor(hex: 0x77745f))) || (exValue.isEqualWithConversion(UIColor(hex: 0xfbe769)))
{
aRange = NSMakeRange(i, 1)
print("yellow")
myValue = styles.yellowHighlightColor()
self.noteTextView.textStorage.addAttribute(attributeName, value: myValue, range: aRange)
saveChanges = true
}
}
}
} // For loop end
我尝试使用 '==' 和这个扩展:
extension UIColor
{
func isEqualWithConversion(_ color: UIColor) -> Bool {
guard let space = self.cgColor.colorSpace
else { return false }
guard let converted = color.cgColor.converted(to: space, intent: .absoluteColorimetric, options: nil)
else { return false }
return self.cgColor == converted
}
}
此外,如果我使用 UIColor.red 或 .blue 或 .green 等标准颜色,它也可以正常工作。
【问题讨论】:
-
This Q&A 可能会有所帮助...
-
@AhmadF 它不起作用
-
UIColor 符合 equatable Equatable 所以你可以说
if colorA == colorB -
我试过了......但仍然不知道为什么......它不起作用
-
我很难处理您的预期结果和实际结果。 “这行不通。” “...重建应用程序。相同的颜色,相同的代码,但它不起作用。”你能解释一下你的意思吗?我可能可以提供一些帮助 - 如果标准颜色有效,您的 RBG 值代码可能会关闭 - 但如果不了解“它不起作用”是什么意思,我不确定。
标签: swift colors compare equals