0

Recently, I was working on a project of mine and I wanted to have multiple labels with the same font, text color, and properties, except their text.

This is the code I wrote:

lazy var profileLabel: UILabel = {
    let label = UILabel()
    label.font = .displayNameLabel
    label.textColor = .profileLabel
    label.numberOfLines = .numberOfLines
    label.textAlignment = .center
    label.translatesAutoresizingMaskIntoConstraints = false

    return label
}()

lazy var displayName: UILabel = {
    let label = profileLabel
    label.text = "Kevin"

    return label
}()

lazy var countryLabel: UILabel = {
    let label = profileLabel
    label.text = "US"

    return label
}()

As you can see, to remedy my issue, I created a single label that had all the properties I wanted for all my other labels. For my other labels, I thought I was creating a new label by typing let label = profileLabel. But as it turns out, I wasn't. After consecutive calls of setting the text and adding the labels to my view, only 1 label was actually displayed, and it was the last label added; so in this case, it would be the countryLabel.

It seems to me that in all my calls to let label = profileLabel, I'm just creating a reference to the same profileLabel. And if this is the case, would changing lazy var profileLabel to var profileLabel fix this issue and create a new label with the needed properties every time profileLabel is called?

1
  • Instead of initialising your property(which creates a single reference point, i.e. an instance), just cut the lazy part and don't add the () at the end of declaration. It will yield the exact behaviour that you're looking for. Refer Subramanian's answer. Commented Dec 6, 2019 at 5:30

1 Answer 1

3

You were intended to use computed property of swift. But didn’t get it right. Your profile label should have been defined as follows.

var profileLabel: UILabel {
   get {
      let label = UILabel()
      label.font = .displayNameLabel
      label.textColor = .profileLabel
      label.numberOfLines = .numberOfLines
      label.textAlignment = .center
      label.translatesAutoresizingMaskIntoConstraints = false
      return label
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.