I made an NSTextField
subclass which adjusts its width with its content length. The idea (of overriding intrinsicContentSize
) is from this question.
override var intrinsicContentSize: NSSize {
if isEditing {
if let fieldEditor =
self.window?.fieldEditor(false, for: self) as?
NSTextView
{
let rect = fieldEditor.layoutManager!.usedRect(
for: fieldEditor.textContainer!
)
let size = rect.size
return size
}
}
let size = self.cell!.cellSize
return size
}
However, there's an extra blank area after the last character. If I set the size.width
manually (size.width -= 3.5
, for example), the text will offset back and forth (horizontally) during editing.
I don't see this quirk in macOS's Finder when renaming its sidebar items. How to get rid of the extra space without making the text "jumping"?
Update 1:
I added a demo on GitHub.
Update 2:
Tried setting NSTextView
's textContainerInset to a size of 0, 0, which doesn't solve the problem.
Update 3:
Updated the repo with @Михаил Масло 's answer. The text still jiggles during editing. The original implementation can be viewed by checking out the initial commit.