cocoa - 当 NSTextField 内容增加时如何调整 NSTextField 大小

标签 cocoa nstextfield nstextview

我有 NSTextField 但我必须显示的内容不是固定的,它会动态增长。 有什么简单的方法可以动态改变大小。 提前致谢:)

最佳答案

文本字段的委托(delegate)需要随着文本的变化而更新大小。

诀窍是您必须手动更新 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)
}

关于cocoa - 当 NSTextField 内容增加时如何调整 NSTextField 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13392349/

相关文章:

cocoa - 强制 NSTextField 中的所有大写字母(Cocoa)

objective-c - 无论如何让(包装)NSTextField 在按下回车键时写一个回车?

objective-c - NSTextAttachmentCell 是一英里高

cocoa - 创建具有可拖动文本元素的 View

ios - 核心数据: Why create a custom persistent store?

objective-c - Cocoa-为什么我应该把我的 statusItem 放在 ApplicationDelegate 中?

swift - 如何禁用 NSTextField 并使其不可编辑? [isEditable 属性不起作用]

cocoa - 为什么我的 Macruby 指针无法作为 void 指针传递?

cocoa - 从 NSToolbarItem 按钮显示 NSPopover

objective-c - 使用什么对象进行特殊文本编辑