Skip to main content

Command Palette

Search for a command to run...

UILabel - how to vertically center

Published
1 min readView as Markdown

Hot tip - you should NEVER need to worry about vertically centering the text in your UILabel.

If you need to, then something has gone a bit funny. Maybe in autoconstraints, or stackviews.

One use case - if you have forced a paragraph style maximum line height, then this will appear as white space ABOVE the text.

And so.. when you start to try and center OTHER text, or views, they will appear off.

The way to fix this is to REMOVE the maximum line height in these instances. Then the text in the UILabel will default back to being vertically centered.

Here's an example of how to reset the max line height to zero, when you have some automatic styling that occurs on your ui labels.

           let titleLabel = UILabel()

           let style = NSMutableParagraphStyle()
            style.maximumLineHeight = .zero
            let attrString = NSMutableAttributedString(string: viewModel.title)
            attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSMakeRange(0, attrString.length))
            titleLabel.attributedText = attrString
43 views

More from this blog

CoderLyn's developer journey

136 posts

I'm an iOS developer, helping millennials with their finances through US neo-bank, Empower.

Before making the switch to development, I was a strategist and GM in the tech space.