Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

ios - How to compare colors in swift

I want change button background for different state. I try so:

 @IBAction func addToShedulerAction(sender: UIButton) {   
       println(sender.backgroundColor)     
        if sender.backgroundColor==UIColor.redColor(){
            sender.backgroundColor==UIColor.whiteColor()
        }
        else //if sender.backgroundColor==UIColor.whiteColor()
        {
            sender.backgroundColor=UIColor.redColor()
        }
    }

but in first push button println print nil and background change to red, in second push println print "Optional(UIDeviceRGBColorSpace 1 0 0 1)" and color doesn't change

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Previous answers are wrong cause

UIColor.black.isEqual(UIColor(red: 0, green: 0, blue: 0, alpha: 1))

returns false

add this code to your project (Swift 4)

extension UIColor {
  static func == (l: UIColor, r: UIColor) -> Bool {
    var r1: CGFloat = 0
    var g1: CGFloat = 0
    var b1: CGFloat = 0
    var a1: CGFloat = 0
    l.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
    var r2: CGFloat = 0
    var g2: CGFloat = 0
    var b2: CGFloat = 0
    var a2: CGFloat = 0
    r.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
    return r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2
  }
}
func == (l: UIColor?, r: UIColor?) -> Bool {
  let l = l ?? .clear
  let r = r ?? .clear
  return l == r
}

so now

UIColor.black == UIColor(red: 0, green: 0, blue: 0, alpha: 1)

returns true

and for you:

if sender.backgroundColor == .red {
  sender.backgroundColor = .white
} else {
  sender.backgroundColor = .red
}

now your code looks pretty :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...