简体   繁体   English

如何在swift中比较颜色

[英]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但是在第一个按钮 println 打印 nil 和背景变为红色,在第二个按钮 println 打印“可选(UIDeviceRGBColorSpace 1 0 0 1)”并且颜色不会改变

Previous answers are wrong cause以前的答案是错误的原因

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

returns false返回false

add this code to your project (Swift 4)将此代码添加到您的项目 (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返回true

and for you:以及对于你:

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

now your code looks pretty :)现在你的代码看起来很漂亮:)

You don't compare colors using the == operator.您不使用==运算符比较颜色。 You do it like this and you need the !你这样做,你需要! to unwrap the optional color:打开可选颜色:

if sender.backgroundColor!.isEqual(UIColor.redColor()) {
            
}

Also, remove the extraneous = in your assignment statement.此外,删除赋值语句中的无关= It should be:它应该是:

sender.backgroundColor = UIColor.whiteColor()

Remember when you are comparing UIColors you have to write description at the end of the color for both side, if you don't write this, every time it will enter into else block.请记住,当您比较UIColors 时,您必须在两侧的颜色末尾写上描述,如果不写,每次都会进入 else 块。 For Example, see the below code例如,请参阅下面的代码

if(ocularPlus1Btn.backgroundColor?.description == UIColor.init(red: 23.0 / 255.0, green: 82 / 255.0, blue: 84 / 255.0, alpha: 1).description) {
   return "positive"
} else {
   return "negative"
}

You have a mistake in your first if clause.您的第一个if子句有误。 It should be:它应该是:

if sender.backgroundColor.isEqual(UIColor.redColor()){
    sender.backgroundColor=UIColor.whiteColor // only one '=' here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM