使用来自iOS 8 / Swift 1的教程创建一个示例应用程序,尝试使用Xcode 7.3 / Swift 2.2将文本分配给标签。提前谢谢。
import UIKit
class ViewController: UIViewController {
@IBOutlet var ageCat: UITextField!
@IBOutlet var resultAge: UILabel!
@IBAction func findAgeButton(sender: AnyObject) {
var enteredAge = Int(ageCat.text!)
var catYears = enteredAge! * 7
resultAge = "Your cat is \(catYears) in cat years"
}
}
答案 0 :(得分:3)
用以下内容替换您的IBAction func findAgeButton:
@IBAction func findAgeButton(sender: AnyObject) {
// Here the variable is unwrapped. This means the code after it is not executed unless the program is sure that it contains a value.
if let text = ageCat.text {
// You can use the unwrapped variable now and won't have to place an exclamation mark behind it to force unwrap it.
let enteredAge = Int(text)
if let age = enteredAge {
let catYears = age * 7
resultAge.text = "Your cat is \(catYears) in cat years"
}
}
}
答案 1 :(得分:0)
感谢所有有用的输入。这对我有用:
@IBAction func findAgeButton(sender: AnyObject) {
var catYears = Int(ageCat.text!)!
catYears = catYears * 7
resultAge.text = "Your cat is \(catYears) in cat years"
}
我还添加了一个if / else来处理nil条目:
if Int(ageCat.text!) != nil {
// --insert last 3 lines of code from above here--
} else {
resultAge.text = "Please enter a number"
}
答案 2 :(得分:-1)
您需要为resultAge.text而不是resultAge:
指定值resultAge.text = "Your cat is \(catYears) in cat years"