我有一个NSTextView
,应该是固定大小的。当文本到达指定帧的底线和右边缘时,我需要设置NSLineBreakByTruncatingTail
以向用户显示椭圆形符号并禁用进一步输入。
当我通过在textStorage
NSTextView
上设置段落样式时,文本向上滚动,我只看到最后一行带有椭圆形符号。我的问题是如何在更改NSTextView
时阻止lineBreakMode
滚动?
谢谢, 纳瓦
编辑:(添加截图)之前:
后:
现在这是执行此操作的代码:
- (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];
}
}
函数widthForHeight
和heightForWidth
是第三方添加的,但效果很好。问题出在我设置NSLineBreakByTruncatingTail
时发生的突然滚动。
这是设置换行模式的功能(也是第三方加入 - 来自一个不错的开发人员(不记得他的名字)):
- (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] ;
}
}