skip to Main Content

I’m trying to center the text of UIButton programmatically.

This is what I want the UIButton to look like (I used the interface builder):

UIbutton

This is what the UIButton looks like after I set it programmatically:

UIbutton

And this is what the UIButton looks like after I set it programmatically and tried to center the text like in the first picture:

UIButton

This is the code that I used to try to center it:

previousPageButton.titleLabel?.numberOfLines = 0

previousPageButton.titleLabel?.textAlignment = .center

2

Answers


  1. The problem was I had set up "attributed" to the title in interface builder. I just had to set it to "plain" and it’s working now.

    Login or Signup to reply.
  2. Do it with new button configuration, set your button:

    let myButton: UIButton = {
        let b = UIButton()
        b.configuration = UIButton.Configuration.filled()
        b.configuration?.title = "CLICK TO GO TOn PREVIOUS PAGE"
        b.titleLabel?.textAlignment = .center
        b.configuration?.baseForegroundColor = .white // text color
        b.configuration?.baseBackgroundColor = .black // background color
        b.configuration?.cornerStyle = .small // corner radius
        b.translatesAutoresizingMaskIntoConstraints = false
        
        return b
    }()
    

    in viewDidLoad set constraints:

    view.addSubview(myButton)
        myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        myButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        myButton.heightAnchor.constraint(equalToConstant: 80).isActive = true // set eight of button
        myButton.widthAnchor.constraint(equalToConstant: 200).isActive = true // set width of button
    

    This is the result:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search