vishrut jain
vishrut jain

Reputation: 35

Change Label.Text programmatically based on the variable calling the function

I am a newbie to swift coding. I am trying to write a clean code. I have multiple label variables I have designed. All the labels have the same UI properties. I am trying to write a single function that I can use for all variables.

I've done individual private lazy var declarations and built function for each label individually. But I am trying to use one function. For example below

private lazy var signUpLabel: UILabel = buildStandardProfileLabel()
private lazy var logInLabel: UILabel = buildStandardProfileLabel()

viewdidLoad() {

view.addsubView(signUpLabel)
view.addSubView(LogInLabel)
}

private func buildStandardProfileLabel() -> UILabel {

let label = UILabel()

label.text = "??" 
}

How do I address the text based on which variable is being called

I just want to use one function to call from both variables SignUp and LogIn but display based on which variable calls the function.

Upvotes: 0

Views: 493

Answers (2)

claude31
claude31

Reputation: 884

Another simple way is to set a tag for each label. Define const such as

let kSignUptag = 0
let kLogInTag = 1

Then in viewDidLoad

signUpLabel.tag = kSignUptag

You can also create an array holding the strings

let labelTexts = ["Sign Up", "Sign In"]

then in buildStandardProfileLabel, use the tag to know which has called.

uiLabel.text = labelTexts[uilabel.tag]

Upvotes: 0

Quinn
Quinn

Reputation: 9434

You could make your function take a parameter for the text:

private lazy var signUpLabel: UILabel = buildStandardProfileLabel(label: "Sign Up")
private lazy var logInLabel: UILabel = buildStandardProfileLabel(label: "Sign In")
private func buildStandardProfileLabel(label: String) -> UILabel {
    let uiLabel = UILabel()
    uiLabel.text = label

    ...

}

Upvotes: 2

Related Questions