bain
bain

Reputation: 355

UIButton text not showing up

I am trying to create UIButton and display a text in it, as well as designate a font size but it will not show up in my Storyboard, using the setTitleColor and the titleLabel!. It will work if I comment those 2 lines out and uncomment the forgot.setTitle (That is currently commented out) however with that I cannot set the UIButton text fontsize. Any suggestions? I have added the subview to my view in my viewdidload.

let forgotPassword: UIButton = {
    let forgot = UIButton()
    forgot.translatesAutoresizingMaskIntoConstraints = false
    //forgot.setTitle("Forgot your password?", for: .normal)

    forgot.titleLabel! .font = UIFont(name:"Forgot your password?", size: 14)
    forgot.setTitleColor(.white, for: .normal)

    forgot.addTarget(self, action: #selector(forgot(_ :)), for: .touchUpInside)
    forgot.sizeToFit()

    //forgot.backgroundColor = .orange
    return forgot

}() 

Upvotes: 1

Views: 1125

Answers (2)

Chris
Chris

Reputation: 4391

The button is not visible because it has no text.

The problem here is that these two lines do not actually set the text, only the appearance.

forgot.titleLabel!.font = UIFont(name: "System", size: 14) // This is the font, not the text itself
forgot.setTitleColor(.white, for: .normal)

You have to call this line as well to actually set any text to appear.

forgot.setTitle("Forgot your password?", for: .normal)

Upvotes: 1

flanker
flanker

Reputation: 4200

You need to uncomment the line that sets the title - without a title it's not surprising that nothing turns up. You also need to change the font line - the name is meant to be the name of the font, not the text string to display. The below works:

let button = UIButton()
button.setTitle("Forgot your password?", for: .normal)
button.sizeToFit()
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
button.setTitleColor(.white, for: .normal)

Upvotes: 1

Related Questions