通过 Cosmicmind 访问 TextField 中的文本

Accessing the text in TextField by Cosmicmind

我在使用 textField 中的文本时遇到一些问题。我已经复制了下面的相关代码(并在这里和那里删除了一些不应该影响我得到的错误的东西)。

我是不是漏掉了什么?我觉得这应该很容易,但我似乎无法弄清楚。

class loginPageViewController: UIViewController, TextFieldDelegate {

private var email: TextField!
private var password: TextField!

func loginButton(sender: RaisedButton!){
    let parameters = [
        "email" : email,
        "password" : password
    ]  

    Alamofire.request(.POST, "https://kidgenius.daycareiq.com/api/v1/sessions", parameters: parameters, encoding: .URL)
    //other alamofire code not relevant to question
}

override func viewDidLoad() {
    super.viewDidLoad()

    prepareEmail()
    preparePassword()
    prepareLoginButton()
}  

private func prepareEmail() {        
    let email : TextField = TextField(frame: 100, 100, 200, 45))
    email.delegate = self
    email.placeholder = "Email"
    //I removed some non relevant code here, just styling stuff
    view.addSubview(email)
}

private func preparePassword() {
    let password : TextField = TextField(100, 200, 200, 25))
    password.secureTextEntry = true
    password.delegate = self
    password.placeholder = "Password"
    //some more removed styling code
    view.addSubview(password)
    }

private func prepareLoginButton() {
    let loginButton : RaisedButton = RaisedButton(frame: 100, 250, 150 , 35))
    loginButton.setTitle("Login", forState: .Normal)
    loginButton.addTarget(self, action: "loginButton:", forControlEvents: UIControlEvents.TouchUpInside)
    //removed some styling code here
    view.addSubview(loginButton)
    }
}

问题是你在顶部声明了你的 email 变量

private var email: TextField!

然后你在函数 prepareEmail() 中再次声明 email

let email : TextField = TextField(frame: 100, 100, 200, 45))

但是您的 private var email: TextField! 永远不会被实例化

为了解决您的问题,请在实例化 prepareEmail()

中的变量时删除 let