如何从Swift中的文本字段获取整数值?
问题描述:
我想创建一个简单的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.
}
}
人有什么想法?我试图寻找解决方案,但找不到特定于此问题的任何内容。
答
使用此:
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
答
的文本字段只接受一个字符串,它不会采取诠释。
更改此:
solutionTextField.text = weightInt/(heightInt*heightInt)
要这样:
solutionTextField.text = String(weightInt/(heightInt*heightInt))
答
我不认为你的代码工作。要从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.
}
}
请记住,这个代码是非常危险的,因为你不能安全地展开自选,但是这是一个不同的线程。
希望这会有所帮助。
答
为了安全,你应该做的“可选绑定”,也检查输入的验证(如果该字符串转换为“内部”):
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...
}
你说你的代码工作。那么你的问题到底是什么? – rmaddy