NSMutableParagraphStyle is ignored in SwiftUI

89 Views Asked by At

When I add attributes such as NSUnderlineStyle.single.rawValue to my string, it adds correctly. But for some reason NSMutableParagraphStyle is ignored. Why is that? Apple bug? Is NSMutableParagraphStyle only available in UIKit?

i made an runnable example that shows the problem, namely that my paragraphStyle.lineSpacing = 50 is ignored, but the underline works as intended.

enter image description here

import SwiftUI

struct SwiftUIView: View {
    let attr: AttributedString = AttributedString("Testing with\nMultiple lines\nbut with incorrect\nrow breaks")
    var body: some View {
        Text(test(text: attr))
    }
}

func test(text: AttributedString) -> AttributedString {
    var combinedAttributedString = AttributedString()

    let indentString = String(repeating: " ", count: 1)
    let bulletPoint = AttributedString(indentString + "• ")
    let attributedText = bulletPoint + text

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 50

    let attributes: [NSAttributedString.Key : Any] = [
        NSAttributedString.Key.paragraphStyle: paragraphStyle,
        NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
    ]

    let nsAttributedString = NSAttributedString(string: String(attributedText.characters), attributes: attributes)
    let attributedString = AttributedString(nsAttributedString)
    combinedAttributedString.append(attributedString)
    combinedAttributedString.append(AttributedString("\n"))
    return combinedAttributedString
}

#Preview {
    SwiftUIView()
}
0

There are 0 best solutions below