滑块在Swift中不会超出当前默认值

时间:2015-05-05 16:00:10

标签: function swift slider calculator updates

很抱歉再次这样做,但我的代码还有另一个问题。当我在模拟器中运行程序时,如果我从默认位置移动滑块并点击提交按钮,它将计算mpg。但是,如果我将滑块保持在默认位置500,那么选择我使用的加仑数(正常情况下),然后点击"提交",我得到mpg的值为0.0。我知道这不对。我的讲师建议我把最初在milesDrivenSliderValueChanged函数中的值放在他们自己的函数中。当我这样做时,我遇到了一堆错误。我修复了它们,但我仍然得到了相同的结果。我想知道我做错了什么。

以下是滑块及其调用的新函数的代码:

class SecondViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate
{
var BlopSoundURL =  NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Blop", ofType: "mp3")!)

var soundAudioPlayer = AVAudioPlayer()

var miles = 0.0
var gallonsUsed = 0.0
var mpg: Double = 0.0
var currentSelection: Double?

@IBOutlet weak var milesDrivenLabel: UILabel!


@IBOutlet weak var milesDrivenSlider: UISlider!

@IBAction func milesDrivenSliderValueChanged(sender: UISlider)
{
    currentSelection = Double(sender.value)

    sliderMoved()
}

func sliderMoved()
{
    milesDrivenLabel.text = "\(round(currentSelection! * 100) / 100)"
    println("Current Selection = \(currentSelection)")
    miles = currentSelection!
}

其余代码用于Picker(我认为没有任何问题),提交按钮和其他功能:

@IBOutlet weak var gallonsUsedPicker: UIPickerView!
let pickerData = [1,2,3,4,5,6,7,8,9,10,11,
            12,13,14,15,16,17,18,19,20,21,
            22,23,24,25,26,27,28,29,30,31,
            32,33,34,35,36,37,38,39,40,41,
            42,43,44,45,46,47,48,49,50,51,
            52,53,54,55,56,57,58,59,60,61,
            62,63,64,65,66,67,68,69,70,71,
            72,73,74,75,76,77,78,79,80,81,
            82,83,84,85,86,87,88,89,90,91,
            92,93,94,95,96,97,98,99,100]

@IBAction func submitButton(sender: UIButton)
{
    soundAudioPlayer.play()
    let rowValue = gallonsUsedPicker.selectedRowInComponent(0) + 1
    gallonsUsed = Double(rowValue)

    mpg = Double(round((miles * 100) / gallonsUsed) / 100)

    let message = "Your MPG is approximately: \(mpg)."

    let alert = UIAlertController(
        title: "Your MPG",
        message: message,
        preferredStyle: .Alert)
    let action = UIAlertAction(
        title: "Ok",
        style: .Default,
        handler: nil)
    alert.addAction(action)
    presentViewController(alert, animated: true, completion: nil)

}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    return "\(row+1)"
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return 100
}


override func viewDidLoad()
{
    super.viewDidLoad()

    gallonsUsedPicker.dataSource = self
    gallonsUsedPicker.delegate = self

    soundAudioPlayer = AVAudioPlayer(contentsOfURL: BlopSoundURL, error: nil)


    // Do any additional setup after loading the view, typically from a nib.
}   // End of viewDidLoad

这真令人沮丧。它可能是一个简单的修复,但我无法看到它。我昨晚花了3个小时,今天早上又花了2个小时。任何帮助,将不胜感激。感谢您的时间和精力。

1 个答案:

答案 0 :(得分:0)

我是一个doofus。我只需要将里程改为500而不是零。现在它有效。对不起,伙计们。