BestGiraffeNigeria BestGiraffeNigeria - 1 year ago 49
Swift Question

One button triggers multiple labels

I am creating a calculator and want a single button to print multiple lines of text. Right now label 1 text is overridden when the button is clicked. I want to utilize label 2 3 and 4 to show more lines of similar texts as to label 1 when the button is clicked

This image shows what i have setup. When i click add course, label 1 line is displayed with the correct information. What i want is the button to use label 2 3 and 4 to display more lines of text as i click add courses

Answer Source

Instead of using multiple labels I would suggest using a UITextView and appending your new text as such:

myTextView.text += "\n You got 100%"

The \n inserts a newline character, making sure that your new text ends up on a new line.


An other way would be to add your labels to an Outlet Collection:

@IBOutlet var labelCollection: [UILabel]!

and then iterating over the labels in a for loop such as this:

for label in labelCollection {
    if label.text.characters.count == 0 {
         label.text = "You got 100%"
    }
}

This would check if label 1 is empty, if it is insert text there, if it is not empty, check label 2, and so on...

I personally would recommend the first approach since it is easier to set up and maintain.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download