Reputation: 81
Quick qeustion, my code:
if (slider2.value == 1)
{
barHeight = 100;
}
else if (slider2.value == 2)
{
barHeight = 200;
}
else if (slider2.value == 3)
{
barHeight = 300;
}
else if (slider2.value == 4)
{
barHeight = 400;
}
else if (slider2.value == 5)
{
barHeight = 500;
}
else
{
barHeight = 600;
}
When I drag the slider from 1 to 6 I see the height of the bar change. But when I move from 6 to 1 the barHeight is stuck at 600 and does not return to 100. What am I missing?
Edit ( full statement ):
- (void)valueAgeChanged:(UISlider*)slider2
{
// DRAW BARS (skeme)
CGRect frame = CGRectMake(595, barX, 80, barHeight);
orangeView= [[UIView alloc] initWithFrame:frame];
orangeView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:orangeView];
// Let slider 1 animate on set value
[slider2 setValue:((int)((slider2.value + 1) / 1.0) - 1.0) animated:NO];
if (slider2.value == 1) {
barHeight = 100;
}else if (slider2.value == 2) {
barHeight = 200;
// barX = 300;
}else if (slider2.value == 3) {
barHeight = 300;
}else if (slider2.value == 4) {
barHeight = 400;
}else if (slider2.value == 5) {
barHeight = 500;
}else if (slider2.value == 6) {
barHeight = 600;
}
}
Upvotes: 0
Views: 1238
Reputation: 4836
You're adding a new orangeView every time your value is changed. So they are simply overlaying each other. The tallest view will remain on screen and when you add shorter views of the same colour you won't see them.
To fix this you could set up the orangeView property outside of your valueChanged method (maybe viewDidLoad) and add it as a subview. Then whenever your slider updates only update the frame of your view.
e.g.
- (void)valueAgeChanged:(UISlider*)slider2
{
[slider2 setValue:((int)((slider2.value + 1) / 1.0) - 1.0) animated:NO];
if (slider2.value == 1) {
barHeight = 100;
}else if (slider2.value == 2) {
barHeight = 200;
// barX = 300;
}else if (slider2.value == 3) {
barHeight = 300;
}else if (slider2.value == 4) {
barHeight = 400;
}else if (slider2.value == 5) {
barHeight = 500;
}else if (slider2.value == 6) {
barHeight = 600;
}
self.orangeView.frame = CGRectMake(595, barX, 80, barHeight);
}
You should also move this to after your if else statement, otherwise it will only update with the previous value.
EDIT: As rmaddy points out the if statement is a bit overkill in this instance. A switch may be more readable/efficient, but as your barHeight is simply the slider value multiplied by 100 it would be much easier to write:
- (void)valueAgeChanged:(UISlider*)slider2
{
barHeight = floorf(slider2.value) * 100;
self.orangeView.frame = CGRectMake(595, barX, 80, barHeight);
}
Upvotes: 6