I'm using NSMutableAttributedString to setup text style. When I set .minimumLineHeight, it centre text in line to the bottom of line. I would like to customise somehow this alignment to centre text in line vertically.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = fontLineHeight // 24 for example
attributedText.addAttribute(.paragraphStyle, value: paragraphStyle, range: fullRange)
The problem with providing a
lineHeight
is that you override the default height-calculation-behaviour with a hardcoded value. Even if you've provided the font's line height as the value, it can vary dynamically based on provided content and it's best to leave this to auto layout (Refer https://stackoverflow.com/a/33278748/9293498)Auto-layout has a solution for these issues most of the time. All you need is a proper constraint setup for your label (and
lineSpacing
in your scenario) which can enable it to scale automatically based on provided text with just-enough space required. BothNSAttributedString
andString
values should workHere's a code sample I've written trying to simulate your requirement:
Views:
Functions:
And here's my constraint setup as I add the above views in
viewDidLoad
:I got the below output:
In the above example, I've used a horizontal stack view to maintain the alignment of text and radio button, which seems efficient to me for your requirement. But the point is, as long as your label is in a properly constrained environment, you don't have the need to manually specify any form of its height.