-1

I am trying to get the text from the text field I have created inside my stackview but I am not able to do it. I was wondering if anyone could help me with this.

for example what I am trying to do is this: when I press a button Label.text = myTextField.text.

This is my code:

var mySttackView: UIStackView = {
    //NAMETEXTFIELD
    let myTextField = UITextField() //<---- want to get the text from this when I press a button but I can't get access to it
    myTextField.translatesAutoresizingMaskIntoConstraints = false
    myTextField.placeholder = "MY TEXT"

    let theStackview: UIStackView = UIStackView(arrangedSubviews: [myTextField])
    theStackview.axis = .vertical
    theStackview.translatesAutoresizingMaskIntoConstraints = false
    theStackview.distribution = .fillEqually
    theStackview.spacing = 12
    return allTextFields
}()
  • Did you try using the `arrangedSubviews` property of the stack view? Show what you did try. – rmaddy Oct 23 '18 at 18:26
  • _" I am not able to do it"_. What happens when you try? – Ashley Mills Oct 23 '18 at 18:26
  • I mean when I am trying to type. label.text = myTextField.text. in ViewDidLoad –  Oct 23 '18 at 18:27
  • The scope of `myTextField` is limited to the closure that creates the stack view (as that's where it's declared). To access it like that you need to declare it as an instance variable of the class. – Ashley Mills Oct 23 '18 at 18:30
  • I would really appreciate it if you could show me what you mean in Code, since I am new to programming and english is not my first language :) –  Oct 23 '18 at 18:32
  • Why are you trying to access the text field in `viewDidLoad`? The user will not have typed anything into the text field yet. – rmaddy Oct 23 '18 at 18:37
  • ow I not in viewDidLoad i mean when i press a button, I am gonna find wa to do that and update this Question –  Oct 23 '18 at 18:39

1 Answers1

2

If you want access to myTextField, declare it outside of the closure that creates the UIStackView.

If myTextField and myStackView are an instance variables, then the myStackView-creating closure can't refer to myTextField unless you also declare myStackView to be lazy.

let myTextField = UITextField()

lazy var myStackView: UIStackView = {
    myTextField.translatesAutoresizingMaskIntoConstraints = false
    myTextField.placeholder = "MY TEXT"

    let theStackview: UIStackView = UIStackView(arrangedSubviews: [myTextField])
    theStackview.axis = .vertical
    theStackview.translatesAutoresizingMaskIntoConstraints = false
    theStackview.distribution = .fillEqually
    theStackview.spacing = 12
    return theStackview
}()
rob mayoff
  • 375,296
  • 67
  • 796
  • 848