我有 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/