我正在开发一个简单的猜谜游戏应用程序,只是为了让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")
}
}
我确定这很简单,但是我在摸不着头脑。
答案 0 :(得分:4)
@IBAction func userInput(sender: UITextField) {
println("This is working")
usersGuess.text = sender.text
}
答案 1 :(得分:1)
虽然我还是iOS dev和Swift的新手,但我想你也可以看一下这个tutorial Apple提供的委托的用法。我想这可能是代码没有辞去你的文本字段的第一响应者状态。因此,usersGuess
无法更新。 (任何知道如何工作的人请发表评论。)
要做到这一点,基本上
UITextField
创建一个插座,例如usersInput
。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")
}
}