3

In a UIStackView, I have four labels corresponding to four IBOutlet variables named lbl_0, lbl_1, lbl_2, lbl_3.

Sometimes, I need to set their value to an empty string. I thought I could do something "flashy" like the following:

// inside a loop body
cell["lbl_"+i].text = ""

but it seems I can't ("no subscript members" error).

So, aside from setting the value this way:

cell.lbl_0.text = ""
cell.lbl_1.text = ""
cell.lbl_2.text = ""
cell.lbl_3.text = ""

is there any other way to set the value of these labels?

3 Answers3

3

@IBOutletCollection

You can connect each label to the same Outlet Collection. To achieve this, drag and drop the first label into the UIViewController, then in the popover dialog set the Connection to Outlet Collection and Name to labelCollection. This will create an array where you can add the other labels.

And finally:

for label in labelCollection {
    label.text = ""
}

or

UILabel subviews

Warning: This will access all labels in the specified view.

for label: UILabel in self.view.subviews.filter({ $0 as? UILabel }) {
    label.text = ""
}
Laffen
  • 2,753
  • 17
  • 29
  • This sounds interesting, I was starting to use the Mirror API to get the members of the custom cell containing the labels... –  Apr 05 '16 at 08:57
  • Update: the second accesses all labels. What if I want to access only the second, the third and the fourth? –  Apr 05 '16 at 09:19
  • 1
    If you have labels in the view that you don't want to edit, I would discourage the use of the latter for-loop and instead go for the `IBOutletCollection`. – Laffen Apr 05 '16 at 09:53
1

My initial thought was that maybe you could do something like

cell.lbl_0.text = cell.lbl_1.text = cell.lbl_2.text = cell.lbl_3.text = ""

But, as it says here in this fine answer

You don't. This is a language feature to prevent the standard unwanted side-effect of assignment returning a value

So...it doesn't seem so, not without using an Outlet Collection as @laffen suggests at least.

But as @matt-gibson suggest in the answer I'm linking to, you can use tuples like so:

(cell.lbl_0.text, cell.lbl_1.text, cell.lbl_2.text, cell.lbl_3.text) = ("", "", "", "")

Which is a tad shorter, but not what you was hoping for I guess :-)

Community
  • 1
  • 1
pbodsk
  • 6,787
  • 3
  • 21
  • 51
0

You could assign a tag to each label and then use UIView's viewWithTag to extract the labels from the UIStackView.

tonisuter
  • 789
  • 5
  • 13