在Swift中,如何将整数转换为字符串并反转并显示结果?

6
该程序应该能够将华氏温度转换为摄氏温度,并实现反向转换。通过开关,打开状态时应该是从摄氏温度转换为华氏温度,关闭状态则应该是从华氏温度转换为摄氏温度。在文本字段中输入下面的数字,在单击提交按钮后,将文本字段中的内容传输到一个整型变量中执行算法,然后在文本字段中显示结果。
我认为转换的过程可能正确无误,但无法显示实际结果。或者转换方法不正确。
@IBOutlet weak var buttonClicked: UIButton!
@IBOutlet weak var mySwitch: UISwitch!
@IBOutlet weak var myTextField: UITextField!

@IBOutlet weak var User: UITextField!



func stateChanged(switchState: UISwitch) {
    if switchState.on {
        myTextField.text = "Convert to Celius"
    } else {
        myTextField.text = "Convert to Farheniet"
    }
}

@IBAction func buttonClicked(sender: UIButton) {
    if mySwitch.on {
        var a:Double? = Double(User.text!)
        a = a! * 9.5 + 32
        User.text=String(a)


        mySwitch.setOn(false, animated:true)
    } else {
        var a:Double? = Double(User.text!)
        a = a! * 9.5 + 32
        User.text=String(a)

        mySwitch.setOn(true, animated:true)
    }

}

1
我首先看到的问题是,无论开关位置如何,您都在将华氏度转换为摄氏度。您还有其他问题吗? - Tyrelidrel
我看到的是,在这两种情况下,转换函数都是错误的。应该是C = (F - 32) * 5 / 9和F = (C * 9 / 5) + 32。 - David Berry
1个回答

4

我正在使用较旧版本的XCode(6.4),因此我的代码与您的略有不同。据我所知,您的函数“buttonClicked”应该采用AnyObject而非UIButton作为参数。另外,在您的代码中根本没有调用函数“stateChanged”。以下代码应该能帮助您实现所需功能。

@IBOutlet weak var mySwitch: UISwitch!
@IBOutlet weak var myTextField: UITextField!

@IBOutlet weak var User: UITextField!



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // sets the textfield to the intended conversion on load.
    if mySwitch.on {
        myTextField.text = "Convert to Celius"
    }
    else {
        myTextField.text = "Convert to Farheniet"
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// changes the myTextFiled text to the intended conversion when the switch is manually switched on or off
@IBAction func switched(sender: AnyObject) {
    if mySwitch.on {
        myTextField.text = "Convert to Celsius"
    }
    else {
        myTextField.text = "Convert to Fahrenheit"
    }
}
// changes the myTextField text to intended reverse conversion after the buttonClicked func is completed.
func stateChanged(switchState: UISwitch) {
if switchState.on {
    myTextField.text = "Convert to Celsius"
}
else {
    myTextField.text = "Convert to Fahrenheit"
    }
}

// do the intended conversion(old version of XCode 6.4)
@IBAction func buttonClicked(sender: AnyObject) {
    if mySwitch.on {
        var a = (User.text! as NSString).doubleValue
        a = (a-32)*(5/9)
        User.text="\(a)"
        mySwitch.setOn(false, animated:true)
        stateChanged(mySwitch)
    }
    else {
        var a = (User.text! as NSString).doubleValue
        a = a * (9/5) + 32
        User.text="\(a)"
        mySwitch.setOn(true, animated:true)
        stateChanged(mySwitch)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接