Ped*_*ira 7 macos cocoa truncate objective-c nstextfield
我已经四处寻找如何执行此操作,但我找不到任何答案.
我想知道我NSTextfield是否已经截断了文本(...在最后),而不必检查其长度stringValue.我需要这样做才能知道我是否应该在我的工具提示上设置NSTextfield(就像一个简单的标签).
我不想检查我的文本字段长度stringValue的原因是因为有些字符比其他字符占用更多的空间,所以这不是很准确
谢谢!
ipm*_*mcc 13
对于将来的访问者,您可以使用该-[NSCell expansionFrameWithFrame:inView:]方法确定是否正在进行截断.从标题:
如果cellFrame对于视图中的整个内容来说太小,则允许单元格返回扩展单元格框架.... <snip> ...如果框架不是太小,则返回一个空的矩形,并且不会显示扩展工具提示视图.默认情况下,返回的NSCell NSZeroRect,而在需要时某些子类(如NSTextFieldCell)将返回正确的框架.
简而言之,你可以判断一个NSTextField是否像这样截断:
NSRect expansionRect = [[self cell] expansionFrameWithFrame: self.frame inView: self];
BOOL truncating = !NSEqualRects(NSZeroRect, expansionRect);
Run Code Online (Sandbox Code Playgroud)
您最好的选择可能是使用 anNSTextView而不是NSTextField。如果您使用,NSTextView您可以获得使用该属性的NSTextContainer信息。容器可以告诉您(绘制文本的空间)。NSTextViewtextContainercontainerSize
NSString对象响应方法sizeWithAttributes:。如果使用给定属性绘制,您可以使用生成的NSSize结构来获取文本的宽度。请参阅NSAttributedString 应用程序工具包添加参考的“常量”部分,了解哪些属性是相关的。
如果containerSize宽度小于sizeWithAttributes:宽度,则文本将被截断。
编辑:抱歉,这仅适用于 no lineFragmentPadding,但默认值lineFragmentPadding非零。减去textContainer.lineFragmentPaddingfromcontainerSize.width或使用NSTextContainer setLineFragmentPadding:方法将其设置为0。
我想您还可以对文本区域相对于文本区域的大小做出一些假设NSTextField,并sizeWithAttributes: NSString结合使用该方法,但这并不那么干净。
编辑2:我意识到我没有解决OP对使用省略号截断文本的兴趣。下面的示例代码在NSTextView. 我还想我不妨添加一些代码,NSTextView通过NSTextField将其放入NSBox. 添加大小检查以确定是否应显示工具提示将是使用上面已经提到的信息对下面的代码进行简单的添加。
NSString* string = @"Hello World.";
// get the size the text will take up using the default font
NSSize textBounds = [string sizeWithAttributes:@{}];
// Create a border view that looks more or less like the border used around
// text fields
NSBox* borderView = [[NSBox alloc] initWithFrame:NSMakeRect(10, 10, 60, textBounds.height+4)];
[borderView setBoxType:NSBoxCustom];
[borderView setBorderType:NSBezelBorder];
[borderView setContentViewMargins:NSMakeSize(0, 0)];
[borderView setFillColor:[NSColor whiteColor]];
// Create the text view
NSTextView* textView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, 60, textBounds.height)];
[textView setTextContainerInset:NSMakeSize(2, 0)];
[textView.textContainer setLineFragmentPadding:0];
[textView setEditable:YES];
// Set the default paragraph style so the text is truncated rather than
// wrapped
NSMutableParagraphStyle* parStyle = [[NSMutableParagraphStyle alloc] init];
[parStyle setLineBreakMode:NSLineBreakByTruncatingTail];
// Do not let text get squashed to fit
[parStyle setTighteningFactorForTruncation:0.0];
[textView setDefaultParagraphStyle:parStyle];
[parStyle release];
// Set text
[textView setString:string];
// add NSTextView to border view
[borderView addSubview:textView];
[textView release];
// add NSBox to view you want text view displayed in
[self addSubview:borderView];
[borderView release];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2781 次 |
| 最近记录: |