Wesley Bryant
Wesley Bryant

Reputation: 99

If Else not allowing color change?

I would like to have 3 If/Else If statements that change the color of a background depending on the value received. So Far my code is:

/////Activity Response Selection/////
@IBAction func ActivityAction(sender: AnyObject) {

    if(ActivitySeg.selectedSegmentIndex == 0)
    {
    ActivityVal.text = "Absent"
    ActivityNum.text = "0"
    }
    else if(ActivitySeg.selectedSegmentIndex == 1)
    {
    ActivityVal.text = "Arms/Legs Flexed"
    ActivityNum.text = "1"
    }
    else if(ActivitySeg.selectedSegmentIndex == 2)
    {
    ActivityVal.text = "Active Movement"
    ActivityNum.text = "2"
    }


let ActivityIn = Double(ActivityNum.text!)
let PulseIn = Double(PulseNum.text!)
let GrimIn = Double(GrimNum.text!)
let AppIn = Double(AppNum.text!)
let RespIn = Double(RespNum.text!)

let product = ActivityIn! + PulseIn! + GrimIn! + AppIn! + RespIn!

TotalVal.text = "\(product)"
TotalVal.text = NSString(format: "APGAR Score: %2.0f", product)as String


if product >= 7.0 {
    TotalVal.backgroundColor = UIColor.greenColor()
}
else if product <= 6.0{
    TotalVal.backgroundColor = UIColor.yellowColor()
}
else if product <= 3.0 {
    TotalVal.backgroundColor = UIColor.redColor()
}

}

Where I have any value greater/equal to 7 as free. Equal/Less than 6 is a yellow background. Equal/Less than 3 is a red background.

My problem lies that the applications will only utilize the Green and Yellow colors, completely ignoring the red. How can I active the red?

Upvotes: 0

Views: 74

Answers (1)

Flying_Banana
Flying_Banana

Reputation: 2910

The problem is your last else if statement.

Your red (<= 3) will also be smaller than 6, so all red ones will be caught in the first else if, never made into the second.

To correct it, you can simply swap the two else if brackets around. Check red first, then yellow.

Or to keep consistency, change it to:

if product >= 7.0 {
    TotalVal.backgroundColor = UIColor.greenColor()
} else if product > 3.0 {
    TotalVal.backgroundColor = UIColor.yellowColor()
} else {
    TotalVal.backgroundColor = UIColor.redColor()
}

Its always a good idea to check for the same inequality signs to avoid this kind of bugs.

Upvotes: 3

Related Questions