Bright Future Bright Future - 27 days ago 10
iOS Question

UISlider ValueChanged action not working

I want to calculate a number in real-time with UISlider, this is my method:

@IBAction func HPsliderValueChanged(_ sender: CustomUISlider) {

calculator.HPPercentage = Double(HPSlider.value)
HPValue.text = String(Int(HPSlider.value * 100)) + " %"
resultLabel.text = String(calculator.calculate())
}


Both the
HPValue
label and
resultLabel
are expected to change value when user swipes on slider, however, now only
HPValue
label changes, the
resultLabel
doesn't work.

calculator
is not nil, here's its code:

class TurretDiveCalculator {

var hero: Heroes = .taka
var build = [DefenseItems](repeatElement(DefenseItems(name: "Empty Item", index: 0, price: 0, image: #imageLiteral(resourceName: "EmptyItem")), count: 6))
var HPPercentage: Double = 0

func calculate() -> Int {
let baseHP = hero.HPLow + (hero.HPHigh - hero.HPLow) / 12 * Double(hero.level)
let baseDefense = hero.armorLow + (hero.armorHigh - hero.armorLow) / 12 * Double(hero.level) + hero.shieldLow + (hero.shieldHigh - hero.shieldLow) / 12 * Double(hero.level)

var buildHP = 0.0
var buildDefense = 0.0
for item in build {
buildDefense += item.armor
buildDefense += item.shield
buildHP += item.HP
}

let fullHP = baseHP + buildHP
var HP = fullHP
let defense = baseDefense + buildDefense
var numberOfShots = 0

while HP > 0 {
let perShotDamageRaw: Double = 330 + Double(numberOfShots) * 0.09 * fullHP
let mitigatedDamage: Double = 0.09 * perShotDamageRaw + 0.9 * perShotDamageRaw / (100 + defense) * 100

HP -= mitigatedDamage
numberOfShots += 1
}

return numberOfShots
}

}


How do I get
resultLabel
's value to change in real-time, too?

Answer

As can be seen in the chat, we managed to find the problem.

This answer is just some general debugging tips and tricks when a problem like this arises.

The original problem was:

now only HPValue label changes, the resultLabel doesn't work.

Lets find out where the problem is. Here's the code:

resultLabel.text = String(calculator.calculate())

Two things can go wrong here:

  1. The resultLabel is not properly wired. To see if that is the case, try setting the value to a plain ol' string and see if you can see that. I you can, well, the textfield is wired properly.

  2. The calculate() method returns an unexpected value. Try verifying what the method returns by adding a print statement just before the return

And as you can see in the chat, once we'd isolated where the problem occurred it was easier for @bright-future to track down the issue.

Hope this helps anybody when they are trying to debug a problem :)