簡體   English   中英

使用Swift將輸入從TextField打印到Xcode中的Label

[英]Printing input from TextField to a Label in Xcode with Swift

我正在開發一個簡單的猜謎游戲應用程序,目的是讓自己更熟悉Swift和Xcode。 我已經能夠在userInput中輸入並獲取它以將消息打印到控制台,但是當我嘗試獲取它以將我的輸入打印到usersGuess(這是一個標簽)時,我無法弄清楚。

這是通過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")
    }


}

我敢肯定這很簡單,但是我正在撓頭。

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

盡管我仍然不熟悉iOS開發人員和Swift,但我想您也可以看看Apple提供的本教程中委托的使用。 我想這可能是代碼沒有放棄您的文本字段的第一響應者狀態。 因此, usersGuess無法更新。 (任何知道此工作方式的人請發表評論。)

為此,基本上

  • UITextField創建一個接收用戶輸入的出口,例如usersInput
  • ViewController設置為usersInput的委托,這將
  • usersInput的第一響應者狀態按下鍵盤上的Return鍵時,輸入。
  • 更新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")
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM