我正在尝试从我在stackview内创建的文本字段中获取文本,但是我无法做到这一点。我想知道是否有人可以帮助我。
例如,我想做的是这样的: 当我按下按钮Label.text = myTextField.text。
这是我的代码:
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
}()
答案 0 :(得分:2)
如果要访问myTextField
,请在创建UIStackView
的闭包之外声明它。
如果myTextField
和myStackView
是实例变量,那么除非创建myStackView
的闭包,否则也不能引用myTextField
,除非您还声明了myStackView
是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
}()