如何从UITextField swift 2.0中捕获文本

时间:2015-11-30 21:29:10

标签: swift uitextfield

我试图简单地捕获键入到支持MainViewController的GameController类中的UITextField的字符串。我下面的代码不会将其捕获到wordAttempt字符串中。也许它与textfield委托有关,我不知道如何设置...非常感谢任何帮助!

Class MainViewController: UIViewController {

required init?(coder aDecoder: NSCoder) {
        controller = GameController()
        super.init(coder: aDecoder)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
 let gameView = UIView(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight))
        self.view.addSubview(gameView)
        controller.gameView = gameView
}

然后

class GameController: NSObject, UITextFieldDelegate {

var gameView: UIView!
var writeText: UITextField!

self.writeText = UITextField(frame: CGRectMake(100,100,200,50))
writeText.delegate = self    
writeText.becomeFirstResponder()
gameView.addSubView(writeText)

textFieldShouldReturn(writeText)
textFieldDidEndEditing(writeText)
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    writeText.resignFirstResponder()
    textFieldDidEndEditing(writeText)
    return true
}

func textFieldDidEndEditing(textField: UITextField) {
    self.wordAttempt = writeText.text ?? ""
    writeText.resignFirstResponder()
}

2 个答案:

答案 0 :(得分:3)

如果您想在任何时候通知用户输入UITextField的某些字符,您应该订阅更改。

// inside your GameController
self.writeText = UITextField(frame: CGRectMake(100,100,200,50))
writeText.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
writeText.becomeFirstResponder()
...
func textFieldDidChange(textField: UITextField) {
  let inputText = textField.text ?? ""
}

您将获得用户在intpuText变量中输入的文字。由于可选类型,您应该在使用前打开它。并且?? ""表示“如果它将空字符串放入intputText,否则为 - text”。这就是您在输出文本时看到Optional("")的原因。

如果您只需要知道用户何时停止输入,请考虑使用UITextFieldDelegate的textFieldDidEndEditing(_:)方法。

class GameController: NSObject, UITextFieldDeleage {
...
    self.writeText = UITextField(frame: CGRectMake(100,100,200,50))
    writeText.delegate = self
    writeText.becomeFirstResponder()
...
  func textFieldDidEndEditing(textField: UITextField) {
    let inputText = textField.text ?? ""
  }

答案 1 :(得分:1)

您需要让它检测到文本已更改。您可以通过单独按下按钮来执行此操作。或者您可以使用textField委托函数textFieldDidEndEditingtextFieldDidBeginEditing来检测文本何时发生更改。请注意,您必须设置文本字段的委托。