iOS: how to set custom background colour with sliders?

[亡魂溺海] 提交于 2019-12-02 12:26:51

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];
}

As UISlider implements the UIAppearence protocol you can set its background color like:

mySlider.backgroundColor = [UIColor lightGrayColor]; // Or any other color

or:

[[mySlider appearance] setBackgroundColor:[UIColor lightGrayColor]];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!