getting a NSTextField to grow with the text in auto layout?

后端 未结 5 1473
有刺的猬
有刺的猬 2020-12-05 08:42

I\'m trying to get my NSTextField to have its height grow (much like in iChat or Adium) once the user types enough text to overflow the width of the control (as asked on thi

5条回答
  •  天涯浪人
    2020-12-05 08:59

    The solution of DouglasHeriot works great for me.

    Here is the same code on Swift 4

    class GrowingTextField: NSTextField {
    
        var editing = false
        var lastIntrinsicSize = NSSize.zero
        var hasLastIntrinsicSize = false
    
        override func textDidBeginEditing(_ notification: Notification) {
            super.textDidBeginEditing(notification)
            editing = true
        }
    
        override func textDidEndEditing(_ notification: Notification) {
            super.textDidEndEditing(notification)
            editing = false
        }
    
        override func textDidChange(_ notification: Notification) {
            super.textDidChange(notification)
            invalidateIntrinsicContentSize()
        }
    
        override var intrinsicContentSize: NSSize {
            get {
                var intrinsicSize = lastIntrinsicSize
    
                if editing || !hasLastIntrinsicSize {
    
                    intrinsicSize = super.intrinsicContentSize
    
                    // If we’re being edited, get the shared NSTextView field editor, so we can get more info
                    if let textView = self.window?.fieldEditor(false, for: self) as? NSTextView, let textContainer = textView.textContainer, var usedRect = textView.textContainer?.layoutManager?.usedRect(for: textContainer) {
                        usedRect.size.height += 5.0 // 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
                        intrinsicSize.height = usedRect.size.height
                    }
    
                    lastIntrinsicSize = intrinsicSize
                    hasLastIntrinsicSize = true
                }
    
                return intrinsicSize
            }
        }
    }
    

提交回复
热议问题