iOS: how to set custom background colour with sliders?

前端 未结 2 497
执念已碎
执念已碎 2021-01-29 00:16

First off I want to say I saw a couple of posts on this site about how to do this, although none seemed to work for me so please don\'t close this down until I get it working.

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-29 01:03

    In your ViewController.h file define

    @property (nonatomic, strong) IBOutlet UISlider *mySlider;
    

    In ViewController.m file, add this:

    - (void) sliderValueChanged:(UISlider *)slider
    {
        // Handle your color changing logic here
        myView.backgroundColor = [UIColor colorWithRed:0.4f green:0.5f blue:1.0f alpha:1.0f];
    }
    

    In Interface Builder, Drag UISlider to view and set its "Value Changed" event outlet to sliderValueChanged method.

    Now as you change the slider on screen, the color should changed based on your logic in the method sliderValueChanged

    Below is the logic as per your requirement:

    - (void) sliderValueChanged:(UISlider *)slider
    {
        // Assuming slider minimum is 0 and maximum is 1
        CGFloat redVal = 0.0f;
        CGFloat yellowVal = 0.0f;
        CGFloat blueVal = 0.0f;
        if (slider == redSlider)
        {
            redVal = slider.value;
        }
        else if (slider == yellowSlider)
        {
            yellowVal = slider.value;
        }
        else if (slider == blueSlider)
        {
            blueVal = slider.value;
        }
        myView.backgroundColor = [UIColor colorWithRed:redVal green:greenVal blue:blueVal alpha:1.0f];
    }
    

提交回复
热议问题