如何在NSTextField中增加内容时调整NSTextField的大小

时间:2012-11-15 06:05:18

标签: cocoa nstextfield nstextview

我有NSTextField,但我必须显示的内容不固定,它会动态增长。 有没有办法以简单的方式动态改变大小。 在此先感谢:)

3 个答案:

答案 0 :(得分:1)

文本字段的委托需要在文本更改时更新大小。

诀窍是你必须手动更新stringValue属性,以避免错误:

override func controlTextDidChange(obj: NSNotification) {
  guard let field = obj.object as? NSTextField else {
    return
  }

  // re-apply the string value, this is necessary for the text field to correctly calculate it's width
  field.stringValue = field.stringValue

  // calculate the new dimensions
  let maxWidth: CGFloat = 500
  let maxHeight: CGFloat = 50
  let size = renameField.sizeThatFits(NSSize(width: maxWidth, height: maxHeight))

  // apply them
  field.frame = NSRect(x: field.frame.origin.x, y: field.frame.origin.y, width: size.width, height: size.height)
}

答案 1 :(得分:0)

如果您只是显示内容,而不是在文本字段中输入内容,那么您应该使用一个标签,该标签可以在IB中设置为"尺寸适合内容"。这将导致标签对于内容来说足够大。

答案 2 :(得分:-1)

没有选项可以通过Interface Builder进行设置。

但是你可以通过代码: 您可以在实现

的NSTextField上设置委托
- (void)controlTextDidChange:(NSNotification *)aNotification;

每次调用委托时,都会按照上面的想法调整控件的大小。

另外,这个。

Jerry Krinock在NSString / NSAttributedString上有一个很棒的类别,允许你根据文本的宽度来计算文本的高度,反之亦然:

http://www.sheepsystems.com/sourceCode/sourceStringGeometrics.html

2016年3月编辑

现在,作为Mac OS应用程序的Autolayout功能有助于增加和减少文本字段甚至NSWindow的大小,因此您可以非常容易地使用它们。只需从Window的任一侧放置约束,并将约束设置为(> = desiredMinimumSize),就完成了!

相关问题