多行 NSTextField 不起作用 [英] Multi-line NSTextField not working
问题描述
我一直在尝试使用 preferredMaxLayoutWidth
让多行 NSTextField
自动布局.我不明白为什么这不起作用.
I have been trying to get a multi-line NSTextField
to lay out automatically using preferredMaxLayoutWidth
. I can’t figure out why this doesn’t work.
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let textField = NSTextField()
textField.cell!.usesSingleLineMode = false
textField.cell!.wraps = true
textField.cell!.lineBreakMode = .byCharWrapping
view.addSubview(textField)
textField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
textField.topAnchor.constraintEqual(to: view.topAnchor),
textField.leadingAnchor.constraintEqual(to: view.leadingAnchor),
textField.widthAnchor.constraintEqual(toConstant: 20)
])
textField.preferredMaxLayoutWidth = 20
textField.stringValue = "abcdefghijklmnopqrstuvwxyz"
view.needsLayout = true
view.layoutSubtreeIfNeeded()
print("Intrinsic content size: (textField.intrinsicContentSize)")
print("Fitting size: (textField.fittingSize)")
}
}
打印出来:
内在内容大小:(-1.0, 21.0)
Intrinsic content size: (-1.0, 21.0)
拟合尺寸:(20.0, 21.0)
Fitting size: (20.0, 21.0)
(21.0 是单行的大小.)
(21.0 is the size for a single line.)
推荐答案
好的.所以事实证明,当 NSTextField
处于编辑模式时,一个秘密的 NSTextView
(又名字段编辑器")将接管编辑部分.在编辑结束之前,文本更改不会同步回文本字段.这就解释了为什么我的示例代码只能在非编辑模式下工作.
OK. So it turns out that when an NSTextField
is in edit mode, a secret NSTextView
(aka the "field editor") takes over for the editing portion. Text changes are not synced back to the text field until editing has ended. This explains why my sample code only works in non-edit mode.
您可以通过访问 NSTextField.stringValue
属性来强制进行同步.这就是我在 NSTextField
子类中所做的.我还提供了我自己的 intrinsicContentSize
实现,因为 Apple 的实现在编辑模式下不起作用,在非编辑模式下也有问题.
You can force the sync to occur by accessing the NSTextField.stringValue
property. This is what I’ve done in a NSTextField
subclass. I also provided my own implementation of intrinsicContentSize
because Apple’s implementation doesn’t work in edit mode and is buggy in non-edit mode.
这篇关于多行 NSTextField 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!