1
votes

I'm trying to display an attributed string using different font sizes with the same line height, here is what I've tried so far:

let paraStyle = NSMutableParagraphStyle()
paraStyle.maximumLineHeight = 30

let username = NSMutableAttributedString(string: user.username, attributes: [
    NSAttributedString.Key.font: UIFont(name: "Oswald-Medium", size: 17) as Any,
    NSAttributedString.Key.foregroundColor: UIColor(named: "DarkColor") as Any,
    NSAttributedString.Key.paragraphStyle: paraStyle
])

let onlineColor = UIColor(named: user.online ? "OnlineColor" : "OfflineColor")
let online = NSMutableAttributedString(string: "• ", attributes: [
    NSAttributedString.Key.font: UIFont.systemFont(ofSize: 24) as Any,
    NSAttributedString.Key.foregroundColor: onlineColor as Any,
    NSAttributedString.Key.baselineOffset: -4
])

let text = NSMutableAttributedString(string: content, attributes: [
    NSAttributedString.Key.font: UIFont(name: "Oswald-Regular", size: 14) as Any,
    NSAttributedString.Key.foregroundColor: UIColor(named: "TextColor") as Any
])

username.append(online)
username.append(text)

Result looks like this, I'd like the first line to have the same height as others.

enter image description here

I've played with lineSpacing and lineHeightMultiple but there's always a gap, any idea on how to fix this?

1

1 Answers

0
votes

Add this in your online and text (NSMutableAttributedString):

    NSAttributedString.Key.paragraphStyle: paraStyle