ReversedcigoL ReversedcigoL - 25 days ago 7
Swift Question

How to get identifier name of a specific control in SWIFT 3 (Created through storyboard) to set values from DB

I have created like a 100+ controls (labels, textboxes, imageviews), using the storyboard (yes I was that patient :( or are there any easier ways to do this lol) for a certain chart and now my problem is how to iterate through the controls using its identifier name (which I did manually by ctrl + draging to the swift file). Is there any way to get its 'identifier name' (like in Android) so I can set values for that specific control w/ the values from my database. E.g:

for i in 0 ..< chartDetails.count{

for view in self.innerView.subviews as [UIView] {
if let txtFld = view as? UITextField{

if(txtFld.identifier == "TXT_L_" + String((i + 1)))
{
txtFld.text = chartDetails[i].ConValue
}
}
}
}


Other solutions said to use the tag, but I don't think it would work in this scenario.

I tried this but got an error, 'unwrapping optional value'

for i in 0 ..< chartDetails.count{

for view in self.innerView.subviews as [UIView] {
if let txtFld = view as? UITextField{

if let value = txt as? UIAccessibilityIdentification{
print("Test: " + value.accessibilityIdentifier!)
}
}
}
}


EDIT:

Thanks to alexburtnik, in order for you to set values in the controls you created, you need to set accessibility of each control programmatically.

enter image description here

Answer

If those controls and labels are similar to each other, you should use a IBOutletCollection for each group instead of individual IBOutlets. In order to do this just select IBOutletCollection when you ctrl & drag the first element in a group to your class. You should see something like this:

@IBOutlet var textFields: [UITextField]!

All subsequent elements of a group you just drag to the same variable and they will be added to the array in runtime.

Now you can iterate over those elements just as you do with any other array:

for textField in textFields {
    if let identifier = textField.accessibilityIdentifier {
        print("Test: " + identifier)
    }
}

Note, that I print only if accessibilityIdentifier exists, so it won't crash as your code. In fact you should avoid forced unwrapping (!) almost everywhere.