samando
samando

Reputation: 139

UIProgressView as health bar and update when button pressed. Swift

So I started making a game and I wanted to use a progress bar as a health bar for many different things and I couldn't figure out why it wasn't updating at all. It did, however, update in the viewdidload function. Here is the code that I am using.

func updateHealthBars() {
    hullHealthBar.setProgress(hullHealth/hullHealthMax, animated: true)
    cannonsHealthBar.setProgress(cannonsHealth/cannonsHealthMax, animated: true)
    sailsHealthBar.setProgress(sailsHealth/sailsHealthMax, animated: true)
    crewHealthBar.setProgress(crewHealth/crewHealthMax, animated: true)

}

@IBAction func setSailButton(sender: AnyObject) {
    if hullHealth > 0 {
        hullHealth-=20
    }
    else if cannonsHealth > 0 {
        cannonsHealth-=20
    }
    else if sailsHealth > 0 {
        sailsHealth-=20
    }
    else if crewHealth > 0 {
        crewHealth-=20
    }
    updateHealthBars()
}

If anybody knows what I need to do to update their health when I press the button, I would be very thankful because I have been trying to do this for a while now without success. I am using XCode 6.

Upvotes: 1

Views: 1102

Answers (2)

samando
samando

Reputation: 139

I finally got this to work. So my original code worked. The actual problem was something to do with my button not being connected right or something even though everything else worked fine. I made a new button and put the same things in it and it worked fine. It was a problem with the button, not the thread or anything.

Upvotes: 0

bsarrazin
bsarrazin

Reputation: 4040

In Swift, when assigning numbers using literals without decimals, it uses Int. ProgressView requires floats. Try the following:

func updateHealthBars() {
    dispatch_async(dispatch_get_main_queue(), ^{
        hullHealthBar.setProgress(hullHealth/hullHealthMax, animated: true)
        cannonsHealthBar.setProgress(cannonsHealth/cannonsHealthMax, animated: true)
        sailsHealthBar.setProgress(sailsHealth/sailsHealthMax, animated: true)
        crewHealthBar.setProgress(crewHealth/crewHealthMax, animated: true)
    });   
}

@IBAction func setSailButton(sender: AnyObject) {
    if hullHealth > 0.0 {
        hullHealth-=20.0
    }
    else if cannonsHealth > 0.0 {
        cannonsHealth-=20.0
    }
    else if sailsHealth > 0.0 {
        sailsHealth-=20
    }
    else if crewHealth > 0.0 {
        crewHealth-=20.0
    }
    updateHealthBars()
}

Make sure your properties are also floats: var hullHealth: Float = 0 or var hullHealth = 0.0

Upvotes: 2

Related Questions