2015-11-19 30 views
6

在Swift中,我如何將int轉換爲字符串並反轉並顯示結果?

該程序假設將F TO C和反轉。使用開關,它會從開到關,然後打開爲C到f,關閉從F到c並在文本字段中輸入下面的#號。 當點擊提交按鈕時,它會將文本字段中的內容傳送給一個in,以執行算法,然後將其顯示在文本字段中。

我相信轉換正確,但不會顯示實際結果。或者它被轉換的方式是錯誤的。

@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

那麼,我馬上看到的第一個問題是,您將F轉換爲C,而不管開關位置如何。你的問題還有更多嗎? – Tyrelidrel

+0

那麼,我所看到的是在這兩種情況下轉換函數都是錯誤的。它應該是C =(F-32)* 5/9和F =(C * 9/5)+32 –

回答

4

我使用舊版本的XCode(6.4),所以我的代碼與你的代碼有點不同。從我的理解你的函數buttonClicked應該採用UIButton的AnyObject instend的參數。你也不會在你的代碼中調用函數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) 
    } 
} 
相關問題