我有6个UITextfields,我想将它们全部放入一个字符串中,这样我就能得到输入到UItextField的内容。
示例:在UItextfield1中,我输入了数字" 3",然后在UItextfield2中,我输入了数字" 5",依此类推。我想把它放到一个字符串中,所以它读取" 35" ....
以下是我的代码。任何帮助都会很棒!
class EnterUsersCode: UIViewController {
var textField1: UITextField! = {
let tf = UITextField()
tf.text = ""
return tf
}()
var textField2: UITextField! = {
let tf = UITextField()
tf.text = ""
return tf
}()
var textField3: UITextField! = {
let tf = UITextField()
tf.text = ""
return tf
}()
var textField4: UITextField! = {
let tf = UITextField()
tf.text = ""
return tf
}()
var textField5: UITextField! = {
let tf = UITextField()
tf.text = ""
return tf
}()
var textField6: UITextField! = {
let tf = UITextField()
tf.text = ""
return tf
}()
var textFieldArray: [UITextField] {
return [textField1!, textField2!, textField3!, textField4!, textField5!, textField6!]
}
答案 0 :(得分:5)
你可以尝试
let str = "\(textField1.text)\(textField2.text)"
或者将所有字符串连接成一个字符串
let str = textFieldArray.compactMap{$0.text}.joined()
答案 1 :(得分:2)
使用textFieldArray
获取文本字段,并通过循环将text
属性中的字符串附加到变量:
func getConsolidatedString() -> String {
var finalString = ""
for textField in textFieldArray {
finalString += textField.text ?? ""
}
return finalString
}
答案 2 :(得分:0)
您可以使用+如下所示连接字符串:
let str = textField1.text + textField2.text + textField3.text + textField4.text + textField5.text + textField6.text