Get values from a textfield array

前端 未结 4 452
难免孤独
难免孤独 2021-01-29 10:07

I would like to access the values of my textfield array but confused as the array I created is with tags. So anyone knows how to get the value of the list (array) I created?

相关标签:
4条回答
  • 2021-01-29 10:18

    Assume that you have array of UITextField

      let textfield1 = UITextField()
            textfield1.tag = 1
            textfield1.text = "1"
    
            let textfield2 = UITextField()
            textfield2.tag = 2
            textfield2.text = "2"
    
            let textfield3 = UITextField()
            textfield3.tag = 3
            textfield3.text = "3"
    
            let arrayOfTextFields :[UITextField] = [textfield2,textfield1,textfield3]
    
            let result = self.getInputsValue(arrayOfTextFields, seperatedby: "-")
    
              print(result)
    

    Method you want :

      func getInputsValue(_ inputs:[UITextField], seperatedby value: String) -> String {
            return inputs.sorted {$0.tag <  $1.tag}.map {$0.text}.compactMap({$0}).joined(separator: value)
        }
    

    Result: 1-2-3

    0 讨论(0)
  • 2021-01-29 10:19

    Let's say you have following array,

        var txtArray:[UITextField] = [UITextField]()
    
        for i in 0...4 {
            let txtField = UITextField(frame: .zero)
            txtField.text = "\(i)"
            txtField.tag = i
            txtArray.append(txtField)
        }
    

    To get values you have to do following,

        let sorted = txtArray.sorted { $0.tag < $1.tag }
        let values = sorted.map { return $0.text! }
        let test = values.joined(separator: " ")
    
        print(test)
    

    Output will be

    0 1 2 3 4
    
    0 讨论(0)
  • 2021-01-29 10:28

    1.Your collection Outlet will be something like this

        @IBOutlet var textFields: [UITextFields]!
    

    2. Sort it by tag

        textFields.sort { $0.tag < $1.tag}
    

    3. Use for loop to get value from array and concatenate it

        var string = ""
    
        for item in textFields {
          string += item.text
        }
    
    0 讨论(0)
  • 2021-01-29 10:31

    Create an outlet connection and connect all your textfields to the same.

    An outlet connection looks like

    @IBOutlet strong var labels: [UILabel]!
    

    Then to get all textfield contents and to append the same.

    var resultString = ""
    for item in enumerate(self.labels) {
       resultString = resultString + item.text
    }
    
    0 讨论(0)
提交回复
热议问题