Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of an NSTextField that expands its height automatically.
import Cocoa
// for AutoLayout
class AutoGrowingTextField: NSTextField {
var minHeight: CGFloat? = 100
let bottomSpace: CGFloat = 5
// magic number! (the field editor TextView is offset within the NSTextField. It’s easy to get the space above (it’s origin), but it’s difficult to get the default spacing for the bottom, as we may be changing the height
var heightLimit: CGFloat?
var lastSize: NSSize?
var isEditing = false
override func textDidBeginEditing(notification: NSNotification) {
isEditing = true
override func textDidEndEditing(notification: NSNotification) {
isEditing = false
override func textDidChange(notification: NSNotification) {
override var intrinsicContentSize: NSSize {
var minSize: NSSize {
var size = super.intrinsicContentSize
size.height = minHeight ?? 0
return size
// Only update the size if we’re editing the text, or if we’ve not set it yet
// If we try and update it while another text field is selected, it may shrink back down to only the size of one line (for some reason?)
if isEditing || lastSize == nil {
guard let
// If we’re being edited, get the shared NSTextView field editor, so we can get more info
textView = self.window?.fieldEditor(false, forObject: self) as? NSTextView,
container = textView.textContainer,
newHeight = container.layoutManager?.usedRectForTextContainer(container).height
else {
return lastSize ?? minSize
var newSize = super.intrinsicContentSize
newSize.height = newHeight + bottomSpace
if let
heightLimit = heightLimit,
lastSize = lastSize
where newSize.height > heightLimit {
newSize = lastSize
if let
minHeight = minHeight
where newSize.height < minHeight {
newSize.height = minHeight
lastSize = newSize
return newSize
else {
return lastSize ?? minSize

This comment has been minimized.

Copy link

aaronraimist commented Sep 20, 2018

Can you please license this in a way where a GPL v3 app can use it? (also cc @DouglasHeriot). I'd love to use this but I don't want to just copy it unless you are fine with that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.