2016-09-27 75 views
0

我想創建一個簡單的BMI計算器,使用身高和體重,我無法將我的UITextField字符串轉換爲整數進行計算。如何從Swift中的文本字段獲取整數值?

這是我的工作代碼:

import UIKit 

class BMICalculator: UIViewController { 
    //MARK: Properties 
    @IBOutlet weak var weightField: UITextField! 
    @IBOutlet weak var heightField: UITextField! 
    @IBOutlet weak var solutionTextField: UILabel! 

    @IBAction func calcButton(_ sender: AnyObject) { 
     let weightInt = Int(weightField) 
     let heightInt = Int(heightField) 

     solutionTextField.text = weightInt/(heightInt*heightInt) 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

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

人有什麼想法?我試圖尋找解決方案,但找不到特定於此問題的任何內容。

+0

你說你的代碼工作。那麼你的問題到底是什麼? – rmaddy

回答

1

使用此:

guard let text1 = weightField.text else { 
    return 
} 

guard let text2 = heightField.text else { 
    return 
} 

guard let weightInt = Int(text1) else { 
    return 
} 

guard let heightInt = Int(text2) else { 
    return 
} 

solutionTextField.text = weightInt /(heightInt*heightInt) 
//Change your name for this outlet 'solutionTextField' to 'solutionLabel' since it is a UILabel not UITextField 
0

的文本字段只接受一個字符串,它不會採取詮釋。

更改此:

solutionTextField.text = weightInt/(heightInt*heightInt) 

要這樣:

solutionTextField.text = String(weightInt/(heightInt*heightInt)) 
0

我不認爲你的代碼工作。要從UITextField s中獲取這些值並將它們轉換爲Ints,您需要將它們從'.text屬性中提取出來。然後,當您計算結果時,您需要將其轉換回字符串,並將solutionTextField?.text設置爲等於該結果。

class BMICalculator: UIViewController { 
    //MARK: Properties 
    @IBOutlet weak var weightField: UITextField! 
    @IBOutlet weak var heightField: UITextField! 
    @IBOutlet weak var solutionTextField: UILabel! 

    @IBAction func calcButton(_ sender: AnyObject) { 
    let weightInt = Int((weightField?.text!)!) 
    let heightInt = Int((heightField?.text!)!) 

    let solution = weightInt!/(heightInt!*heightInt!) 

    solutionTextField?.text = "\(solution)" 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

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

請記住,這個代碼是非常危險的,因爲你不能安全地展開自選,但是這是一個不同的線程。

希望這會有所幫助。

0

爲了安全,你應該做的「可選綁定」,也檢查輸入的驗證(如果該字符串轉換爲「內部」):

if let weightInt = weightField.text where Int(weightInt) != nil, let heightInt = heightField.text where Int(heightInt) != nil { 
    // you can do "String Interpolation" to get the solution string: 
    // now it is fine to use the "Force Unwrapping", already checked 
    let solution = "\(Int(weightInt)!/(Int(heightInt)! * Int(heightInt)!))" 
    solutionTextField.text = solution 
} else { 
    // invalid input... 
} 
相關問題