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

后端 未结 5 1466
有刺的猬
有刺的猬 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:49

    This solution also works when setting the string value of the text field and when it's resized by AutoLayout. It just uses the attributed text property to calculate the intrinsic content size whenever it's needed.

    class AutoGrowingTextField: NSTextField {
        var maximumHeight: CGFloat = 100
    
        override var intrinsicContentSize: NSSize {
            let height = attributedStringValue.boundingRect(
                with: NSSize(width: bounds.width - 8, height: maximumHeight),
                options: [NSString.DrawingOptions.usesLineFragmentOrigin]
                ).height + 5
    
            return NSSize(width: NSView.noIntrinsicMetric, height: height)
        }
    
        override func textDidChange(_ notification: Notification) {
            super.textDidChange(notification)
            invalidateIntrinsicContentSize()
        }
    
        override func layout() {
            super.layout()
            invalidateIntrinsicContentSize()
        }
    }
    

提交回复
热议问题