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

Son*_*nny 6 swift

该程序假设改变F到C并反转.使用Switch,它从on变为off和on,假设是C到f,off是F到c,并在文本字段中输入#underneath.单击提交按钮时,它会在文本字段中显示什么,将其传输到预制算法中,然后将其显示在文本字段中.

我相信转换正确但不会显示实际结果.或者它被转换的方式是错误的.

@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)
    }

}
Run Code Online (Sandbox Code Playgroud)

小智 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)
    }
}
Run Code Online (Sandbox Code Playgroud)