Get values from a textfield array

回眸只為那壹抹淺笑 提交于 2021-02-05 12:15:17

问题


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?

I want to create a function where I : Get the value of the textfields on a list Sort them by tags get the value of each individual textfield concatenate them in a string


回答1:


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
    }



回答2:


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
}



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/50643429/get-values-from-a-textfield-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!