laishere
laishere

Reputation: 145

How to fix iOS custom shaped text layout incorrect ellipse behavior?

I am learning iOS textkit from official tutorials here: https://developer.apple.com/documentation/uikit/textkit/display_text_with_a_custom_layout

After running and testing the code for a while, I found an incorrect ellipse beahavior:

Incorrect ellipse behavior

The code uses one-length flexible space control-character following the ellipse character to push the rest of the chars to the next line by setting its width equal to the rest of the line width.

However, as shown above, it failed to do so. I think that's because the line break policy determines to squeeze a bit of room for the following period even there's no room, which is a correct policy for common case. But it's clearly not what we want in this case.

So, the problem is how to correct it.

Upvotes: 0

Views: 38

Answers (1)

laishere
laishere

Reputation: 145

I come up with 2 ways to solve the problem.

  1. Using more flexible spaces.

    // CircleTextViewController+Ellipsis.swift line 50
    // let flexibleSpaceCharRange = NSRange(location: flexibleSpaceCharIndex, length: 1)
    let flexibleSpaceCharRange = NSRange(location: flexibleSpaceCharIndex, length: 2)
    

    By using more flexible spaces makes sure that the character following the first flexible space is another space that won't be squeezed in the same line by line break policy.

  2. Make all characters after flexible space at the same line into control characters.

    // CircleTextViewController+Ellipsis.swift line 130
    /*
    for index in  flexibleSpaceStartIndex..<flexibleSpaceStartIndex + flexibleSpaceIntersection.length {
        finalProps[index - glyphRange.location] = .controlCharacter
    } */
    for index in (flexibleSpaceStartIndex - glyphRange.location)..<glyphRange.length {
        finalProps[index] = .controlCharacter
    }
    

    Now, because the implementation of boundingBoxForControlGlyphAt method will make the width of all control characters except flexible space become 0, we hide all characters at the same line after the flexible space.

Correct result:

Correct ellipse behavior

Upvotes: 0

Related Questions