![](/img/trans.png)
[英]Label -> Alert Controller Textfield? Can I edit pre-existing text from a label, in a textfield in an alert controller? Swift 3, Xcode 8, IOS
[英]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.