简体   繁体   中英

iOS: how to set custom background colour with sliders?

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.

What I want to do is make the background of the view change depending on the value of the sliders are, so that the user can choose the background colour they want.

self->colorView.backgroundColor = [UIColor myColor];
myColor = 

I figure I'll need a bit of code like that, although I don't know how to define what my colour will be something; like "red: redSlider / 255" and so on for the other colours? I also don't know where to implement the code above as I need it to continuously update when the use changes the values of the sliders.

I am quite basic at programming as you may have picked up because I'm only a teenager doing it as a hobby and I'd appreciate simple instructions telling me clearly where I need to put code etc.

ps It won't let me post an image of the view, sorry :(

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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