2016-04-25 10 views
1

iOS 8/Swift 1のチュートリアルを使用して、Xcode 7.3/Swift 2.2を使用して、ラベルにテキストを割り当てるためのサンプルアプリケーションを作成します。前もって感謝します。コード内のテキストをUILabelに割り当てます! 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" 

    } 
} 

答えて

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" 
    } 
    } 
} 
+0

あなたはテキストが数値であることを確認し、アンラップ力を 'tの必要があります。 – LoVo

+0

上記のコードを使用した後、私はこのエラー "不変の値 'catYears'の初期化は使用されませんでした; '_'への代入に置き換えたり、削除することを検討してください。テキストフィールドに "3"を入力すると、catYears = 140316326775648となります。 "catYearsに"スレッド1:ブレークポイント2.1 3.1を、 "resultAge.text ="の次の行にテキストが赤くなります。シミュレータではラベルは変更されません。あなたのコードは良く見えますが、私は何を知っていますか? VMとしてXcodeを動作させることが重要なのかどうかは疑問です。 –

+0

おい、食べ物の束が間違っている!最初の問題から始めましょう。 「_」について不平を言っているもの。 resultAge.text = "あなたの猫は猫の年に\(catYears)です" –

-1

あなたはresultAge.text代わりのresultAgeに値を代入する必要があります。すべての役に立つ入力用

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

速くこれを文字列補間といいます。 –

+0

どのように名前を付けても構いませんが、依然としてOPが質問したように、 – glace

+0

のように質問しましたが、(resultAge)はUIlabel変数であり、ラベルに値を直接代入しています。 UILabelにはテキストを割り当てるための "Text"というプロパティがあります。だからそれを見てください。 –

0

感謝を。これが私の仕事:

@IBAction func findAgeButton(sender: AnyObject) { 

    var catYears = Int(ageCat.text!)! 

    catYears = catYears * 7 

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

    } 

を私もエントリーnilを対処する場合/他の追加:

if Int(ageCat.text!) != nil { 

    // --insert last 3 lines of code from above here-- 

    } else { 

    resultAge.text = "Please enter a number" 

} 
関連する問題