将NSTextField的preferredMaxLayoutWidth与自动布局一起使用

时间:2018-10-19 18:37:18

标签: swift xcode autolayout nstextfield

我正在尝试获取一个NSTextField,以根据视图周围的文字大小自动调整其高度。我能够获得的最接近的结果是实现layout()函数并将preferredMaxLayoutWidth的值设置为当前框架的大小,但这仅在视图增长时起作用。

文本字段仅限于主视图的开头,结尾和顶部锚点,填充为50:

Window before dragging the width

我可以拖动窗口的右侧以增加宽度,NSTextField可以正确调整其宽度(自动布局)和高度,但是之后我不能再缩小窗口了:

Window after dragging the width

任何帮助我都非常感激,因为我花了很长时间来解决这个问题。

let myTextField: NSTextField = NSTextField()

class myView: NSView {

    override func layout() {

        super.layout()
        myTextField.preferredMaxLayoutWidth = myTextField.frame.width
        super.layout()
    }

    required init?(coder decoder: NSCoder) {

        super.init(coder: decoder)

        self.wantsLayer = true
        self.layer?.backgroundColor = NSColor.green.cgColor

        myTextField.wantsLayer = true
        myTextField.layer?.backgroundColor = NSColor.yellow.cgColor
        myTextField.bezelStyle = .roundedBezel
        myTextField.isEditable = false
        myTextField.isBordered = false
        myTextField.textColor = NSColor.black
        myTextField.translatesAutoresizingMaskIntoConstraints = false
        myTextField.preferredMaxLayoutWidth = 50
        self.addSubview(myTextField)
        myTextField.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 50).isActive = true
        myTextField.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -50).isActive = true
        myTextField.topAnchor.constraint(equalTo: self.topAnchor, constant: 50).isActive = true
        myTextField.stringValue = "The width of the inspector is variable and is user controlled. It is not controlled (nor defined by) any constraints. Only the gray views and the NSTextField labels in the screenshots are using auto layout. (And all of this is done in code, not in Interface Builder.) I'll re-visit subclassing and manually doing layout in layout but I was hoping to minic the wrapping behavior seen in Finder's Get Info panel using only constraints."

    }
}

0 个答案:

没有答案