I have a NSTextView
, which is supposed to be fixed size. When the text comes to the bottom line and to the right edge of the designated frame I need to set the NSLineBreakByTruncatingTail
in order to present user with elliptic signs and disable further typing.
When I do this through setting a paragraph style on textStorage
of NSTextView
the text scrolls up and I see only the last line with elliptic signs in the end. My question is how to prevent NSTextView
from scrolling when changing its lineBreakMode
?
Thanks, Nava
EDIT: (added screenshots) Before:

After:

Now here's the code that does it:
- (void)textDidChange:(NSNotification *)notification
{
NSString *text = [textView string];
CGFloat width, height;
NSRect newFrame = self.frame;
width = round([text widthForHeight:newFrame.size.height font:textView.font]);
height = round([text heightForWidth:newFrame.size.width font:textView.font]);
if (height > newFrame.size.height && width > newFrame.size.width) {
NSTextContainer *textContainer = textView.textContainer;
[textContainer setWidthTracksTextView:NO];
[textContainer setHeightTracksTextView:NO];
[textView setHorizontallyResizable:NO];
[textView setVerticallyResizable:NO];
[textView setAutoresizingMask:NSViewNotSizable];
[textView setLineBreakMode:NSLineBreakByTruncatingTail];
}
}
Functions widthForHeight
and heightForWidth
are some 3rd party additions, which work well. The problem is in this sudden scroll that happens when I set NSLineBreakByTruncatingTail
.
Here's the function, that sets the line break mode (also 3rd party addition - from a nice developer (don't remember his name)):
- (void)setLineBreakMode:(NSLineBreakMode)lineBreakMode {
NSDictionary* curAttributes = [[self textStorage] attributesAtIndex:0
effectiveRange:NULL];
NSParagraphStyle *currentStyle = [curAttributes objectForKey:NSParagraphStyleAttributeName];
if (currentStyle.lineBreakMode != lineBreakMode) {
NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy] ;
[paragraphStyle setLineBreakMode:lineBreakMode] ;
NSMutableDictionary* attributes = [[[self textStorage] attributesAtIndex:0
effectiveRange:NULL] mutableCopy] ;
[attributes setObject:paragraphStyle
forKey:NSParagraphStyleAttributeName] ;
[paragraphStyle release] ;
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:[self string]
attributes:attributes] ;
[attributes release] ;
[[self textStorage] setAttributedString:attributedString] ;
[attributedString release] ;
}
}
来源:https://stackoverflow.com/questions/8921858/nslinebreakbytruncatingtail-scrolls-text-when-set-as-a-paragraph-style-in-nstext