以编程方式创建的UItextfield,稍后如何在Swift中获取文本?

时间:2019-02-23 19:01:28

标签: ios swift uitextfield

我在viewDidAppear类中以编程方式创建了一个UITextField,如下所示:

let userfield: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 500.00, height: 30.00));
userfield.backgroundColor = UIColor.white
userfield.borderStyle = UITextField.BorderStyle.roundedRect
userfield.keyboardType = .emailAddress
userfield.placeholder = "Email"
view.addSubview(userfield)

但是,当我尝试在另一个函数中调用该文本字段时,该字段没有问题:

@objc func buttonregisteraction(sender: UIButton!) {
    if let username = userfield.text, let password = password.text 

我收到此错误:“未解析的标识符'userfield'”

我见过同样的问题,但仅在Objective-C中。

2 个答案:

答案 0 :(得分:0)

您已将userfield声明为仅在viewDidAppear内部可用的变量。您需要使其成为视图控制器的属性。

class YourViewController: UIViewController {
    var userfield: UITextField! // declare it here

    override func viewDidLoad() {
        super.viewDidLoad()

        userfield = UITextField(frame: CGRect(x: 0, y: 0, width: 500.00, height: 30.00));
        userfield.backgroundColor = UIColor.white
        userfield.borderStyle = UITextField.BorderStyle.roundedRect
        userfield.keyboardType = .emailAddress
        userfield.placeholder = "Email"
        view.addSubview(userfield)
    }
}

现在,您可以通过视图控制器中的任何方法(包括按钮操作)访问userfield

答案 1 :(得分:0)

Swift 4.2

将此代码用于文本字段和属性。您可以添加更多属性。

lazy var textExample: UITextField = {
        let textFiled = UITextField()
        textFiled.text = "how you doing man?"
        textFiled.frame = CGRect(x: 100, y: 100, width: 100, height: 30)
        textFiled.font = UIFont.boldSystemFont(ofSize: 12)
        textFiled.textAlignment = .left
        textFiled.textColor = .blue
        textFiled.layer.borderColor = UIColor.blue.cgColor
        textFiled.layer.borderWidth = 1
        return textFiled
    }()

然后像这样添加视图:

override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(button)
    }

希望这很简单:)