skip to Main Content

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


  1. 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)")
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search