Ios 将代码中的文本指定给UILabel!Swift 2.2

Ios 将代码中的文本指定给UILabel!Swift 2.2,ios,swift,swift2,uilabel,Ios,Swift,Swift2,Uilabel,使用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

使用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"

    }
}

将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"
   }
  }
}

您需要为resultAge.text而不是resultAge赋值:

resultAge.text = "Your cat is \(catYears) in cat years"      

感谢所有有用的输入。这对我很有用:

@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"

}

你应该确保文本是数字的,而不是力展开的。在使用上面的代码之后,我得到了这个错误:“不可变值的初始化”CATESS从未被使用过;考虑用赋值替换为“或”。在文本字段中输入“3”将导致CATYERS=140316326775648。在“let catYears”行之后获取线程1:断点2.1 3.1,“resultAge.text=”后面的下一行文本为红色。标签在模拟器中不会改变。我觉得你的代码不错,但我知道什么。想知道作为虚拟机运行Xcode是否是一个因素。好吧,很多东西都出了问题!让我们从第一期开始。抱怨'的东西。你确定你有这一行吗?:resultAge.text=“你的猫是(猫年)猫年”在swift中,这被称为字符串插值。不管你如何命名,这仍然不是OP问的问题,因为你看到了这个问题,请看,(resultAge)是UIlabel变量,他直接给标签赋值。UILabel有一个属性“Text”向其添加文本。所以请看里面。