user2816600
user2816600

Reputation: 277

How do I change the background color of a button as I move a slider?

I currently am struggling to get the background color of my button to change as my slider reaches a certain point. I want the background color to change from orange to blue as my slider value reaches one, but right now it is only changing color if I press the button. Help Please :)

This is what i currently have:

- (IBAction)buttonChange:(id)sender {
if ([_statuslabel.text isEqualToString:@"Temperature: 1"]) {
    [_myButton setBackgroundColor: [UIColor blueColor]] ;

Upvotes: 0

Views: 1342

Answers (2)

Jack
Jack

Reputation: 16865

From my interpretation of your question, you are using a UISlider and you call this function on touchupinside.

To update it continuously, implement a valuechanged function

-(IBAction)sliderValueChanged:(UISlider*)slider {
    if (slider.value > 0.5)
        slider.backgroundColor = [UIColor blueColor];
    else
        slider.backgroundColor = [UIColor orangeColor];
}

Then in interface builder connect this to the sliders "Value Changed" outlet

Upvotes: 0

Georg
Georg

Reputation: 3930

To get a constant change of your buttons color you could use this code:

- (IBAction)sliderValueChanged:(UISlider *)sender
{
    CGFloat blueHue = 232.0f;  // should be kind of blue
    CGFloat orangeHue = 32.0f; // should be kind of orange

    CGFloat resultingHue = ((blueHue - orangeHue)) * sender.value + orangeHue;

    self.yourButton.backgroundColor = [UIColor colorWithHue:resultingHue / 360.0f
                                                 saturation:1
                                                 brightness:1
                                                      alpha:1];
}

Just connect your UISlider in IB and set the sliderValueChanged: method for the Value Changed event.

Using the HSV (http://en.wikipedia.org/wiki/HSL_and_HSV) model should be the easiest solution to archive what you want.

Hope this helps

Upvotes: 1

Related Questions