I have an NSTextView for editing a long string without spaces, but with punctuation characters. I'd like it to wrap at whatever character falls at the end of the line instead of trying to split it into words where it finds punctuation, which results in uneven lines.
I thought it would be as easy as making a subclass of NSATSTypesetter
to reimplement this method like so开发者_运维技巧:
- (BOOL) shouldBreakLineByWordBeforeCharacterAtIndex:(NSUInteger)charIndex {
return YES;
}
This is not having any effect on the layout of the text view. It is being called once for every line break on every layout, but only where the line break would have occurred anyway.
The line breaking setting in a NSTextView is actually a attribute of the text in it's textStorage.
You need to get the NSTextStorage of that view which is a NSMutableAttributedString then set that string's style to your needed line break setting.
Keep in mind the text in the storage keeps changing and the text itself contains the setting so you need to keep setting it on each change.
Call this method below as [self setLineBreakMode:NSLineBreakByCharWrapping forView:txtView]; every time the text storage is changed, e.g.: KVO observe txtView.string
-(void)setLineBreakMode:(NSLineBreakMode)mode forView:(NSTextView*)view
{
NSTextStorage *storage = [view textStorage];
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:mode];
[storage addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, [storage length])];
[style release];
}
精彩评论