Get multiple Textfield values in array in swift (Xcode)

I have 10 textfields in my storyboard and I want to fetch values of them and store it into an array using loops so that I don't want to write hard code for each textfield using swift 4 (Xcode) . var arr = [Int]() let val1 = Int(TxtVal1.text ?? "0") ?? 0 let val2 = Int(TxtVal2.text ?? "0") ?? 0 let val3 = Int(TxtVal3.text ?? "0") ?? 0 let val4 = Int(TxtVal4.text ?? "0") ?? 0 let val5 = Int(TxtVal5.text ?? "0") ?? 0 arr = [val1,val2,val3,val4,val5]

don't want to do it like that

2 answers

  • answered 2021-01-11 05:30 Mahendra

    You can assign tags to the UITextField and then store that textfield's value to array.

    Set the tags to textfields

        txtField1.tag = 101
        txtField1.tag = 102
        //and so on
    

    Create and initialise array to store text of textfields

        var arrText = [String]()
    
    
        //textfield tag are set from 101 to 110
        
        for tag in 101...110 {
            
            if let txtField = view.viewWithTag(tag) as? UITextField, let txt = txtField.text {
                arrText.append(txt)
            }
        }
    
    print("array = \(arrText)")
    

  • answered 2021-01-11 05:30 Raja Kishan

    Use @IBOutlet collection. Bind your all UITextField with the @IBOutlet collection.

    Example:

    class ViewController: UIViewController {
    
        @IBOutlet var textFields: [UITextField]!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            let arrTextValue = textFields.compactMap{Int($0.text ?? "0")}
            
            print(arrTextValue)
        }
    }
    

    enter image description here