How to get a button to listen for a segmented control in Swift?

I am trying to create a temperature conversion application. I used segmented control for users to choose how the temperature should be calculated (Celsius to Fahrenheit and from Fahrenheit to Celsius). I also created a button that converts the temperature entered by the selected method into a segmented control.

Here is the function I created in the controller:

@IBAction func convertTemp(sender: AnyObject) {
    let t = Double(tempTextfield.text!)
    let type = converterType.selectedSegmentIndex
    let tempM = tempModel(temp:t!)

    if type == 0 {
        finalTemp.text = String(tempM.celsius2Fahrenheit())
    }

    if type == 1 {
        finalTemp.text = String(tempM.fahrenheit2Celsius())
    }
}

And this is what I have in my model.

class tempModel {
  var temp: Double

  init (temp:Double){
    self.temp = temp
  }
  func celsius2Fahrenheit()->Double{
    return 32 + temp * 5 / 9;
  }
  func fahrenheit2Celsius()->Double{
    return (temp - 32) * 5/9;  
  }
}

I'm not sure what I'm doing wrong. Everything except Button(convert)works the way I want it to work. I can't seem to find a mistake.

And I don't know if this helps, but I get this error:

2015-11-16 18: 07: 02.496 TemperatureConverer [5201:194432] , 8 iPhone-Portrait-DecimalPad; 4131139949_Portrait_iPhone-Simple-Pad_Default
2015-11-16 18: 07: 04.827 TemperatureConverer [5201:194432] keyplane, 8 iPhone-Portrait-DecimalPad; 4131139949_Portrait_iPhone-Simple-Pad_Default (lldb)

+4
1

. viewController tempModel. , tempModel . .

@IBAction func convertTemp(sender: AnyObject) {

    let temp = Double(tempTextfield.text!)!
    var newTemp = ""

    if converterType.selectedSegmentIndex == 0{
        newTemp = String(format: "%.2f Farenheit", 32+temp*5/9)
    }
    if converterType.selectedSegmentIndex == 1{
        newTemp = String(format: "%.2f Celsius",(temp-32)*5/9)
    }
    finalTemp.text = newTemp
}

, , . , , .

+2

Source: https://habr.com/ru/post/1616144/


All Articles