[英]how to make NSTextField to fit NSMutableAttributedString contained
I have a NSTextField where I add NSMutableAttributedString. 我有一个NSTextField,在其中添加NSMutableAttributedString。 I want to set the size of that string to big number, however when I do that the text appears cut off.
我想将该字符串的大小设置为大数字,但是当我这样做时,文本似乎被截断了。 How can tell the NSTextField to get bigger?
如何告诉NSTextField变大?
This is what I have: 这就是我所拥有的:
NSTextField* textField = [[NSTextField alloc] init];
NSMutableAttributedString* text = [[NSMutableAttributedString alloc]
initWithString:@"0"];
NSRange titleRange = NSMakeRange(0, [text length]);
[text addAttribute:NSFontAttributeName
value:[NSFont boldSystemFontOfSize:25]
range:titleRange];
[textField setAttributedStringValue:text];
Any advice? 有什么建议吗? Thanks in advance
提前致谢
Make a subclass of NSTextField 制作NSTextField的子类
In implementation do override intrinsicContentSize 在实现中,请重写nativeContentSize
-(NSSize)intrinsicContentSize
{
if ( ![self.cell wraps] ) {
return [super intrinsicContentSize];
}
NSRect frame = [self frame];
CGFloat width = frame.size.width;
frame.size.height = CGFLOAT_MAX;
CGFloat height = [self.cell cellSizeForBounds: frame].height;
return NSMakeSize(width, height);
}
// Than invalidate the layout when text changes
- (void)textDidChange:(NSNotification *)notification
{
[super textDidChange:notification];
[self invalidateIntrinsicContentSize];
}
In attribute Inspector inside storyboard set NSTextField class to your customNSTextField class and change layout to wraps from scrolls. 在情节提要内部的属性Inspector中,将NSTextField类设置为customNSTextField类,然后将布局更改为从滚动换行。 You must add constraints to your textField to its superview, easier in storyboard.
您必须将textField的约束添加到其superview,在情节提要中更容易。
After that you can also set font size directly : 之后,您还可以直接设置字体大小:
[_textField setFont:[NSFont systemFontOfSize:25]];
[textField sizeToFit];
但是使用自动布局通常是一个更好的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.