2014-11-22 113 views
2

我正在研究一個簡單的猜謎遊戲應用程序,只是爲了讓Swift和Xcode更加舒適。我已經能夠在userInput中輸入,並讓它向控制檯打印消息,但是當我嘗試將它輸入到usersGuess(這是一個標籤)時,我無法弄清楚。將TextField中的輸入從Swift輸入到Xcode中的標籤

這裏有一個單一視圖的應用程序中我的代碼通過的Xcode:

import UIKit 

class ViewController: UIViewController { 
    @IBOutlet weak var correctAnswerLabel: UILabel! 
    @IBOutlet weak var usersGuess: UILabel! 

    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. 
    } 

    @IBAction func buttonPressed() { 
     correctAnswerLabel.text = "Changes when the button is pressed." 
    } 

    @IBAction func userInput(sender: UITextField) { 
     println("This is working") 
    } 


} 

我敢肯定,這是簡單的,但我抓我的頭笑。

+0

看你的代碼,我看不出什麼毛病。所以我最好的選擇是你檢查'correctAnswerLabel'是否實際上已經連線(看到該行左邊的小點,是否填滿了?)。還要確保你已經正確連接了這個'buttonPressed'動作的目標動作。並仔細檢查標籤是否實際顯示在屏幕上(您可以將背景顏色設置爲橙色或綠色以便於檢查)。 – sikhapol 2014-11-23 06:06:07

回答

3
@IBAction func userInput(sender: UITextField) { 
    println("This is working") 
    usersGuess.text = sender.text 
} 
+0

我知道這可能是違反SOF的規則,但如何混合兩個不同的輸出到控制檯,如在java中: System.out.println(「輸入的年齡是:」+年齡); xcode: print(「輸入的年齡是:」* age.text) – raja777m 2015-12-18 00:39:14

+0

對於Swift我使用:print(「文本是:\\(sender.text)」)。還沒有嘗試過你的例子。 – mbo42 2015-12-28 08:27:57

1

雖然我還是新到iOS開發和斯威夫特,我想你也可以看看這個tutorial蘋果使用委託的提供。我想這可能是代碼沒有退出你的文本字段的第一響應者狀態。因此,usersGuess無法更新。 (任何人誰知道這項工作,請如何發表評論。)

要做到這一點,基本上

  • 創建接收用戶的輸入,也就是說,usersInputUITextField的出口。
  • 設置ViewController作爲usersInput一個代表,這將是按下鍵盤上的回車鍵時
  • 辭職usersInput的第一響應狀態。
  • 更新usersGuess的文字。

代碼在這裏:

import UIKit 

class ViewController: UIViewController, UITextFieldDelegate { 
    @IBOutlet weak var correctAnswerLabel: UILabel! 
    @IBOutlet weak var usersGuess: UILabel! 
    @IBOutlet weak var usersInput: UITextField! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     // Set ViewController as a delegate 
     usersInput.delegate = self 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    // Here are the callback functions for usersInput 
    func textFieldShouldReturn(textField: UITextField) -> Bool { 
     textField.resignFirstResponder() 
     return true 
    } 

    func textFieldDidEndEditing(textField: UITextField) { 
     usersGuess.text = textField.text 
    } 

    @IBAction func buttonPressed() { 
     correctAnswerLabel.text = "Changes when the button is pressed." 
    } 

    @IBAction func userInput(sender: UITextField) { 
     println("This is working") 
    } 

}