tl;dr: Using UIButton.Configuration
- do titleAlignment = .center
but also add a subtitle and make its font microscopic.
So, we're on iOS 15+, we're using the new UIButton.Configuration
APIs, buttons now go multi-line by default and you're trying to figure out - how do I make the button's title be centered or trailing aligned, as opposed to the default (leading). For example you have an image and a button title underneath and and you want it centered.
Seems reasonable to try this:
configuration.titleAlignment = .center
But it doesn't change anything.
By trying thing out in Interface Builder, I noticed the following: titleAlignment
only has an effect if there is a subtitle along with the title.
I am not sure if this is an omission on Apple's side (which might be fixed later) or if there is a good reason for it. In any case, we need a way to make it work without a subtitle. Perhaps some clever contentInset
or UIControl.contentHorizontalAlignment
can do the trick, but I'd be worried to use these in cases where we have to think about other languages, dynamic type etc.
Here's a solution which is still hacky, but would do the job:
Add a subtitle
which contains just a space, then make the font microscopic, e.g. 0.01
.
This is how to do it in code, assuming you are already working with a UIButton.Configuration
:
configuration.titleAlignment = .center
configuration.title = "Hello hi"
configuration.subtitle = " "
configuration.subtitleTextAttributesTransformer = UIConfigurationTextAttributesTransformer({ input in
var output = input
output.font = .systemFont(ofSize: 0.01)
return output
})
Not an ideal solution and it might break in the future, but for some use cases the best available solution at the moment.