使用IF语句更改图像

时间:2014-07-13 21:01:40

标签: ios objective-c if-statement uiimage

我在游戏中设置了一个燃料棒,但是我试图使用if语句根据燃料百分比的低点来改变条形图像。出于某种原因,图像不随百分比变化。因此,酒吧仍然满员。这是怎么回事?

fuelRemaining = 100;
    FuelRemaining.text = [NSString stringWithFormat:@"%i%%", fuelRemaining];
    FuelBar.image = [UIImage imageNamed:@"fuel_bar_100.png"];
    if (fuelRemaining > 90) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_100.png"];
    }
    else if (fuelRemaining > 80 && fuelRemaining <= 90) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_90.png"];
    }
    else if (fuelRemaining > 70 && fuelRemaining <= 80) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_80.png"];
    }
    else if (fuelRemaining > 60 && fuelRemaining <= 70) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_70.png"];
    }
    else if (fuelRemaining > 50 && fuelRemaining <= 60) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_60.png"];
    }
    else if (fuelRemaining > 40 && fuelRemaining <= 50) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_50.png"];
    }
    else if (fuelRemaining > 30 && fuelRemaining <= 40) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_40.png"];
    }
    else if (fuelRemaining > 20 && fuelRemaining <= 30) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_30.png"];
    }
    else if (fuelRemaining > 10 && fuelRemaining <= 20) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_20.png"];
    }
    else if (fuelRemaining > 0 && fuelRemaining <= 10) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_10.png"];
    }
    else {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_0.png"];
    }

1 个答案:

答案 0 :(得分:3)

首先,通过一些基本数学简化:

int fuelRounded = 10.0 * floor((fuelRemaining/10.0)+0.5);
NSString *fuelImageString = [NSString stringWithFormat:@"fuel_bar_%d.png", fuelRounded];
FuelBar.image = [UIImage imageNamed:fuelImageString];

(数学可能需要调整,具体取决于您的游戏逻辑和fuelRemaining的可能值。)

其次,您似乎在方法的顶部将fuelRemaining设置为100。在fuelRemaining更改为其他内容后,您需要再次设置图像。

例如:

- (void) updateFuelViews {
    FuelRemaining.text = [NSString stringWithFormat:@"%i%%", fuelRemaining];

    int fuelRounded = 10.0 * floor((fuelRemaining/10.0)+0.5);
    NSString *fuelImageString = [NSString stringWithFormat:@"fuel_bar_%d.png", fuelRounded];
    FuelBar.image = [UIImage imageNamed:fuelImageString];
}

每次[self updateFuelViews];更改时都会致电fuelRemaining

您可能希望研究键值观察,这样可以在fuelRemaining更改时自动更新燃料视图。这有点令人头疼,但如果你有很多东西不断变化,可以让你更容易管理。