Search code examples
cocoanstextfieldnstextview

How to resize NSTextField when content increase in NSTextField


i have NSTextField but content that i have to show is not fixed , it will grow dynamically. is there any way in simple way through which we can change size dynamically. Thanks in Advance :)


Solution

  • The text field's delegate needs to update the size as the text changes.

    The trick is you have to manually update the stringValue property, to avoid bugs:

    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)
    }