我无法将UITextField
转换为Int
,但我已经查看了互联网上的说明。我是Swift 2的初学者。有人可以帮忙吗?
import UIKit
class ViewController: UIViewController {
@IBOutlet var age: UITextField!
@IBOutlet var resultLabel: UILabel!
@IBAction func findAge(_ sender: AnyObject) {
// Changed "enteredAge = age" to "enteredAge = age!"
var age = Int = Int(age.text)
var enteredAge = Int(age)
if enteredAge != nil {
var catYears = enteredAge! * 7
resultLabel.text = "Your cat is \(catYears) in cat years"
} else {
resultLabel.text = "Please enter a number in the box"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:0)
输入年龄再次使用age.text,如年龄变量
答案 1 :(得分:0)
正如我在您的代码中看到的那样,您正在重新声明年龄文本字段,我正在编辑您的IBAction。我没有运行此代码,但我认为它对您有用。只需在代码中复制粘贴即可。
@IBAction func findAge(_ sender: AnyObject) {
var ageToInt = Int(self.age.text!)!
if ageToInt != nil {
var catYears = ageToInt! * 7
resultLabel.text = "Your cat is \(catYears) in cat years"
} else {
resultLabel.text = "Please enter a number in the box"
}
}
祝你好运!