user19020059
user19020059

Reputation:

Center alignment UIButton xCODE programmatically

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

Upvotes: 0

Views: 455

Answers (2)

Fabio
Fabio

Reputation: 5648

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 TO\n 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

Upvotes: 0

user19020059
user19020059

Reputation:

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.

Upvotes: 1

Related Questions