【问题标题】:Assign Text in Code to UILabel! Swift 2.2将代码中的文本分配给 UILabel!斯威夫特 2.2
【发布时间】:2016-05-08 09:55:54
【问题描述】:

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

    }
}

【问题讨论】:

    标签: ios swift swift2 uilabel


    【解决方案1】:

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

    【讨论】:

    • 你应该确保文本是数字并且不要强制展开。
    • 使用上面的代码后,我收到此错误“从未使用过不可变值 'catYears' 的初始化;考虑替换为 '_' 的赋值或删除它”。在文本字段中输入“3”会导致 catYears = 140316326775648。在“let catYears”行之后得到线程 1:断点 2.1 3.1,“resultAge.text =”之后的下一行文本为红色。标签在模拟器中没有变化。您的代码对我来说看起来不错,但我知道什么。想知道将 Xcode 作为 VM 运行是否是一个因素。
    • 好吧,一堆东西出了问题!让我们从第一个问题开始。抱怨'_'的东西。你确定你有这行吗?:resultAge.text = "你的猫是 (catYears) in cat years"
    【解决方案2】:

    感谢所有有用的意见。这对我有用:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 在swift中这称为字符串插值。
      • 不管你怎么命名,它仍然不是 OP 要求的
      • 如您所见,请查看 (resultAge) 是 UIlabel 变量,他直接为 label 赋值。 UILabel 有一个属性“Text”来为其分配文本。所以请看一下。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      相关资源
      最近更新 更多