I have tried everything I found on StackOverflow but nothing worked really. I need to calculate boundingRect's height for any/random UIFont available.
The code is simple (I modified some of the code to be more readable):
let ps = NSMutableParagraphStyle()
ps.lineBreakMode = NSLineBreakMode.byWordWrapping
ps.alignment = NSTextAlignment.center
ps.lineSpacing = 0
ps.paragraphSpacingBefore = 0
ps.paragraphSpacing = 0
let myRandomFont = geMyRandomFont(name: randomFontName, size: myFontSize)
let attrParams = [
NSAttributedString.Key.font: myRandomFont,
NSAttributedString.Key.paragraphStyle: ps
] as [NSAttributedString.Key : Any]
let ns = NSString(string: text)
let toUseForDrawingBounds = ns.boundingRect(
with: CGSize(width: boundsSize.width, height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attrParams,
context: nil
)
In rare cases (for some UIFonts) it works ok, but for most of the other fonts toUseForDrawingBounds.height is almost always 1 blank line too big.
(my input string text is always trimmed with whitespacesAndNewlines)
EDIT 2: After some testing I noticed this was not the case. With every UIFont (different combinations of font sizes & text) it can happen the returned height is 1 blank line too big. When I calculated number of lines (toUseForDrawingBounds.height / font.lineHeight) I clearly saw that sometimes returned number of lines was 1 too many.
I have tried tricks (StackOverflow) with (sizeToFit, etc.) UITextViews, UILabels, etc. Nothing really worked. Any ideas?
EDIT: To give a clear example, look at the attached image. Yellow rectangle approx. represents returned toUseForDrawingBounds bounds. I need proper bounds height so I can draw text vertically centered.