如何将文本字段的值传递给Swift3中单击按钮的函数?

如何将文本字段的值传递给Swift3中单击按钮的函数?,swift3,Swift3,我需要在按下登录按钮时进行用户名和登录检查。我需要通过编程来完成所有这些。无论如何,我的问题是,当我创建一个连接到函数的按钮时,文本字段就超出了范围 import UIKit class ViewController: UIViewController { var usernameTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() let use

我需要在按下登录按钮时进行用户名和登录检查。我需要通过编程来完成所有这些。无论如何,我的问题是,当我创建一个连接到函数的按钮时,文本字段就超出了范围

import UIKit

class ViewController: UIViewController {

    var usernameTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let usernameTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
        usernameTextField.center = CGPoint(x: 160, y: 80)
        usernameTextField.placeholder = "username"
        usernameTextField.text = ""
        usernameTextField.borderStyle = UITextBorderStyle.line
        usernameTextField.backgroundColor = UIColor.white
        usernameTextField.textColor = UIColor.blue
        self.view.addSubview(usernameTextField)



        let button = UIButton(type: UIButtonType.system) as UIButton

        let xPostion:CGFloat = 10
        let yPostion:CGFloat = 200
        let buttonWidth:CGFloat = 150
        let buttonHeight:CGFloat = 45

        button.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight)

        button.backgroundColor = UIColor.lightGray
        button.setTitle("Submit", for: UIControlState.normal)
        button.tintColor = UIColor.black
        button.addTarget(self, action: #selector(ViewController.buttonAction(_:)), for: .touchUpInside)

        self.view.addSubview(button)


    }



    func buttonAction(_ sender:UIButton!) {

        let username = usernameTextField.text

        print("Username value is \(String(describing: username))!")
        print("Button tapped")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

如何在buttonAction函数中获取usernameTextField

usernameTextField
未超出范围,您的应用程序将崩溃,因为您在
viewDidLoad
中使用局部变量隐藏了该名称的属性。 您应该将
let
-行更改为
usernameTextField=
,这不会创建同名的局部变量,而是为属性赋值:

override func viewDidLoad() {
    super.viewDidLoad()

    usernameTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
    usernameTextField.center = CGPoint(x: 160, y: 80)
    usernameTextField.placeholder = "username"
    usernameTextField.text = ""
    usernameTextField.borderStyle = UITextBorderStyle.line
    usernameTextField.backgroundColor = UIColor.white
    usernameTextField.textColor = UIColor.blue
    self.view.addSubview(usernameTextField)

    ...

}