iOS: how to set custom background colour with sliders?

浪子不回头ぞ 提交于 2019-12-20 05:41:03

问题


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.

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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/14020764/ios-how-to-set-custom-background-colour-with-sliders

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