Search code examples
iosswiftuicolor

Comparing 2 UIColor(s)


This must have been asked before, but I cannot find a suitable reference. I have found this question, but that compares three numbers with each other.

I am trying to compare 2 UIColor(s) to avoid duplication. Each color is referenced in r, g, b, alpha. I form the colors so I can control number formatting.

What would be the appropriate way to handle this?


Solution

  • If you are creating all color the same way you can just use ==.

    If your colors are in different color spaces and you just want to compare their RGBA value use the following:

    extension UIColor {
        func equals(_ rhs: UIColor) -> Bool {
            var lhsR: CGFloat = 0
            var lhsG: CGFloat = 0
            var lhsB: CGFloat = 0
            var lhsA: CGFloat = 0
            self.getRed(&lhsR, green: &lhsG, blue: &lhsB, alpha: &lhsA)
    
            var rhsR: CGFloat = 0
            var rhsG: CGFloat = 0
            var rhsB: CGFloat = 0
            var rhsA: CGFloat = 0
            rhs.getRed(&rhsR, green: &rhsG, blue: &rhsB, alpha: &rhsA)
    
            return  lhsR == rhsR &&
                    lhsG == rhsG &&
                    lhsB == rhsB &&
                    lhsA == rhsA
        }
    }
    

    For instance:

    let white1 = UIColor.white
    let white2 = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 1)
    white1 == white2 //false
    white1.cgColor == white2.cgColor //false
    white1.equals(white2) //true