简体   繁体   中英

Which characters does NSLineBreakByWordWrapping break on?

Short version

From the docs:

NSLineBreakByWordWrapping

Wrapping occurs at word boundaries, unless the word itself doesn't fit on a single line.

What is the set of all word boundary characters?

Longer version

I have a set of UILabels, which contain text, sometimes including URLs. I need to know the exact location ( frame , not range ) of the URLs so that I can make them tappable. My math mostly works, but I had to build in a test for certain characters:

    // This code only reached if the URL is longer than the available width
    NSString *theText = // A string containing an HTTP/HTTPS URL
    NSCharacterSet *breakChars = [NSCharacterSet characterSetWithCharactersInString:@"?-"];
    NSString *charsInRemaininsSpace = // NSString with remaining text on this line

    NSUInteger breakIndex = NSNotFound;

    if (charsInRemaininsSpace)
        breakIndex = [charsInRemaininsSpace rangeOfCharacterFromSet:breakChars
                                                            options:NSBackwardsSearch].location;

    if (breakIndex != NSNotFound && breakIndex != theText.length-1) {
        // There is a breakable char in the middle, so draw a URL through that, then break
        // ...
    } else {
        // There is no breakable char (or it's at the end), so start this word on a new line
        // ...
    }

The characters in my NSCharacterSet are just ? and -, which I discovered NSLineBreakByWordWrapping breaks on. It does not break on some other characters I see in URLs like % and =. Is there a complete list of characters I should be breaking on?

I recommend using "not alphanumeric" as your test.

[[NSCharacterSet alphanumerCharacterSet] invertedSet]

That said, if you're doing a lot of this, you may want to consider using CTFramesetter to do your layout instead of UILabel . Then you can use CTRunGetImageBounds to calculate actual rects. You wouldn't have to calculate your word breaks, since CTFrame will already have done this for you (and it would be guaranteed to be the same algorithm).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM