如何从Swift中的文本字段中获取整数值?

时间:2016-09-27 15:26:25

标签: ios swift uitextfield

我想使用高度和重量创建一个简单的BMI计算器,但我无法将UITextField字符串转换为整数进行计算。

这是我的工作代码:

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.
    }
}

有人有什么想法吗?我尝试搜索解决方案,但找不到任何特定于此问题的内容。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

TextField只接受一个String,它不会采用Int。

改变这个:

solutionTextField.text = weightInt/(heightInt*heightInt)

对此:

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

答案 2 :(得分:0)

我认为您的代码无法运行。要从UITextField中获取值并将其转换为Ints,您需要将它们从&{39;} .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.
    }
}

请注意,此代码非常危险,因为您不能安全地展开选项,但这是一个不同的主题。

希望这有帮助。