I have a UIViewController with multiple UIViews named view0, view1, view2… After a parsing queue my app retrieve a parsedArray and must change single views background color depending on its value. To avoid long if…else routines I wanna use switch…case statement: so, what’s the best way to manage these multiple UIViews names into the switch…case statement? An extension? I know I could use Collection views or UIStackViews but I’ve already a lot of methods focused on single UIViews, and btw I’d like to learn the best way to manage multiple names in a type name like UIView. Thanks!
func colorViews() {
for i in 0...21
{
switch (parsedArray[i]) {
case "0": viewX.backgroundColor = .systemRed // HERE X MUST BE i
default:
viewX.backgroundColor = .systemGreen // HERE X MUST BE i
}
}
3
Answers
As suggested by Joakim comment, the solution is easier than I thought: a simple Array of names, and I post it to further reference. Thank you to the other suggestions, I'll study better.
In the controller scope:
In viewDidLoad() func:
In the switch...case statement:
one solution if you do not want to change your current structure, you can use view ids. When you generate your viewX’s, just add a id to it with the same value of the view’s number.
This is a sample:
After that you can access your views like:
Either have your views placed in array or create a function that returns you a view for given index.
An array approach looks like this:
and you would have your method like
A function that returns a view with index would look like so
and you would use it like so