0

快速提问,我的代码:

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

当我将滑块从 1 拖动到 6 时,我看到栏的高度发生了变化。但是当我从 6 移动到 1 时,barHeight 停留在 600 并且不会返回到 100。我错过了什么?

编辑(完整声明):

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


}
4

1 回答 1

6

每次更改值时,您都会添加一个新的 orangeView 。所以它们只是相互叠加。最高的视图将保留在屏幕上,当您添加相同颜色的较短视图时,您将看不到它们。

要解决此问题,您可以在 valueChanged 方法(可能是 viewDidLoad)之外设置 orangeView 属性并将其添加为子视图。然后,每当您的滑块更新时,只会更新您的视图框架。

例如

- (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);

}

你也应该把它移到你的 if else 语句之后,否则它只会用之前的值更新。

编辑:正如 rmaddy 指出的那样, if 语句在这种情况下有点矫枉过正。开关可能更具可读性/效率,但由于您的 barHeight 只是滑块值乘以 100,因此编写起来会容易得多:

- (void)valueAgeChanged:(UISlider*)slider2
{

barHeight = floorf(slider2.value) * 100;
self.orangeView.frame = CGRectMake(595, barX, 80, barHeight);

}
于 2013-05-16T10:53:28.663 回答