Search code examples
cocoaautolayoutnstextfield

Why does the intrinsicContentSize of my NSTextField not change as I enter characters?


I am trying to achieve a custom NSTextField that resizes horizontally (without wrapping text) as text is added to the NSTextField. The Content Compression Resistance Priority property should be able to assist in the above (I have set this to 1000) but it is actually having no effect.

That gets me to the title of my question: I call intrinsicContentSize within the overridden keyUp() method of my custom NSTextField but it shows that intrinsicContentSize is not changing - I am pretty sure that for content Compression Resistance to work it would need to have a changing intrinsicContentSize.

EDIT

As Ken Thomas's points out below, NSTextField does not have an intrinsic width so I shouldn't have expected it to change as I entered more characters. Below is the code I have added to make it change though:

override var intrinsicContentSize:NSSize{
    return NSMakeSize(self.attributedStringValue.size.width + 20, 20)
}

override func textDidChange(notification: NSNotification) {
    super.textDidChange(notification)
    self.invalidateIntrinsicContentSize()
}

Solution

  • Unless you've attempted to alter the default behavior, editable text fields don't have an intrinsic width. That is, textField.intrinsicContentSize.width == NSViewNoInstrinsicMetric. That's because when a text field is editable, its content is not intrinsic, it's extrinsic.