Search code examples
iosline-breaksnsattributedstring

Why NSLineBreakByWordWrapping splits word?


With using NSAttributedString, I tried to create text inside a triangle as below;

http://postimg.org/image/rp9fukgaj/

I used "NSLineBreakByWordWrapping" method for fitting text inside defined shape. But first word of text splits and I couldn't found a solution for that. I want my text jumps to the following line instead of splitting. How can I do that?

Below the code I used;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor blackColor];
    CTFontRef fontRef = CTFontCreateWithName((CFStringRef)@"HelveticaNeue-Regular", 15.0f, NULL);     
    NSMutableParagraphStyle* paragraph = [NSMutableParagraphStyle new];
    paragraph.headIndent = 10;
    paragraph.firstLineHeadIndent = 10;
    paragraph.tailIndent = -10;
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    paragraph.alignment = NSTextAlignmentCenter;
    paragraph.paragraphSpacing = 15;    
    NSDictionary *attrDictionary = [NSDictionary dictionaryWithObjectsAndKeys: (__bridge id)fontRef, (NSString *)kCTFontAttributeName, (id)[[UIColor whiteColor] CGColor], (NSString *)(kCTForegroundColorAttributeName),paragraph,NSParagraphStyleAttributeName, nil];    
    CFRelease(fontRef);
    NSAttributedString *attString = [[NSAttributedString alloc] initWithString:@"Initially, now I create the paragraph style and apply it to the first character. Note how the margins are dictated: the tailIndent is negative, to bring the right margin leftward, and the firstLineHeadIndent must be set separately, as the headIndent does not automatically apply to the first line." attributes:attrDictionary];
    [(CustomView *)[self view] setAttString:attString];
}

Solution

  • Checking out the documentation for NSLineBreakMode, apparently if the word will not fit on a given line, the word will get broken up to fit. If your text is static, you could probably just insert a newline character to skip the first part of the triangle; otherwise, you'll have to be clever to figure out how to overcome this limitation.