Box House
Box House

Reputation: 177

How to put multiple UITextFields into one string on Swift 4?

I have 6 UITextfields and I would like to put them all into one string so I can get what was inputted into the UItextField.

Example: In UItextfield1, I entered the number "3", then in UItextfield2, I entered the number "5", and so on. I would like to put this into one string so it reads "35" ....

Below is my code. Any help would be great!

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!]

}

Upvotes: 3

Views: 2176

Answers (3)

Parth Barot
Parth Barot

Reputation: 363

You can concatenate your string by using + like below:

let str = textField1.text + textField2.text + textField3.text + textField4.text + textField5.text + textField6.text

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100551

You can try

 let str = "\(textField1.text)\(textField2.text)"

or to get all strings concatenated in one string

let str = textFieldArray.compactMap{$0.text}.joined()

Upvotes: 8

badhanganesh
badhanganesh

Reputation: 3463

Use your textFieldArray to get the textfields and append the string from text property to a variable by looping through it:

func getConsolidatedString() -> String {
    var finalString = ""
    for textField in textFieldArray {
        finalString += textField.text ?? ""
    }
    return finalString
}

Upvotes: 2

Related Questions