Search code examples
iosswiftuilayoutfonts

Text with custom font truncated


I use the custom font "Zapfino" in my app, but the texts sometimes get truncated as shown in the picture below. Usually the text frame (colored red below) automatically expands with the contained text - but this does not seem to work for (some) custom fonts:

Text(name)
    .font(Font.custom("Zapfino", size: 48, relativeTo: .title))
    .foregroundColor(Color.white)
    .baselineOffset(48)
    .padding(10)
    .background(Color.red)

Example text "Test-f" which appears truncated

Any ideas how to fix this? I tried to set the frame size explicitly, but it did not work.


Solution

  • I managed to adjust the SwiftUI related code from stackoverflow.com/a/64565207/6257435 to my needs. In order to enable automatic truncation of the text I defined a maximum intrinsic size that is considered accordingly:

    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize
        size.width = min(size.width + clipExtension.width, maxIntrinsicContentSize.width)
        size.height = min(size.height + clipExtension.height, maxIntrinsicContentSize.height)
        return size
    }
    

    Otherwise the intrinsic size always extended to the text length and thus the text was never truncated.