NSTextField And AutoLayout: Autogrow height -> Programmatically

前端 未结 2 1164
执笔经年
执笔经年 2021-01-20 10:42

If I create a label in interface builder and set a string through code that does not fit its current size, the label will grow vertically to fit its size, great!. Besides th

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-20 11:02

    I think a better way to do this, is to override NSTextField, and update the intrinsicContentSize.

    public class DynamicTextField: NSTextField {
       public override var intrinsicContentSize: NSSize {
          if cell!.wraps {
             let fictionalBounds = NSRect(x: bounds.minX, y: bounds.minY, width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
             return cell!.cellSize(forBounds: fictionalBounds)
          } else {
             return super.intrinsicContentSize
          }
       }
    
       public override func textDidChange(_ notification: Notification) {
          super.textDidChange(notification)
    
          if cell!.wraps {
             validateEditing()
             invalidateIntrinsicContentSize()
          }
       }
    }
    

    Afterwards the constraints works as expected. Note that it only works when you set the Layout to Wraps in Interface Builder or code.

提交回复
热议问题