gpt4 book ai didi

ios - 如何从以编程方式添加的 UITextView 获取文本 [Swift]

转载 作者:行者123 更新时间:2023-11-29 01:52:11 26 4
gpt4 key购买 nike

我使用以下代码添加文本字段,以将 3 个 UITextField 添加到 ViewController:

for var index = 0; index < 3; ++index {
var textField = UITextField(frame: CGRectMake(0, 0, 300, 40))
var pom:CGFloat = 130 + CGFloat(index*50)
textField.center = CGPointMake(185, pom)
textField.layer.borderWidth = 1.0;
textField.layer.cornerRadius = 5.0;
textField.textAlignment = NSTextAlignment.Center
self.view.addSubview(textField)
}

现在我需要从所有文本字段中获取文本。谁能告诉我,我该怎么做?

最佳答案

您可以将它们存储在一个数组中,使用循环中计数器的值在每个数组上设置 tag 属性,然后稍后通过该标记检索它们:

class MyViewController: UIViewController {

var textFields = [UITextField]()

override func viewDidLoad() {
super.viewDidLoad()

for var index = 0; index < 3; ++index {
var textField = UITextField(frame: CGRectMake(0, 0, 300, 40))
var pom:CGFloat = 130 + CGFloat(index*50)
textField.center = CGPointMake(185, pom)
textField.layer.borderWidth = 1.0;
textField.layer.cornerRadius = 5.0;
textField.textAlignment = NSTextAlignment.Center
textField.tag = index
self.textFields.append( textField )
self.view.addSubview(textField)
}

for var index = 0; index < 3; ++index {
if let textField = self.textFieldForTag( index ) {
print( textField.text )
}
}
}

func textFieldForTag( tag: Int ) -> UITextField? {
return self.textFields.filter({ $0.tag == tag }).first
}
}

关于ios - 如何从以编程方式添加的 UITextView 获取文本 [Swift],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31281352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com