How to move or resize an NSView by setting the frame property?

旧巷老猫 提交于 2021-01-29 20:42:05

问题


I created the NSView in a storyboard. In this case, it is an NSTextField. In the NSViewController's viewDidLoad() method, I want to conditionally resize and reposition the NSTextField, but setting the frame has no effect.

For example:

class ViewController: NSViewController {

    @IBOutlet var label: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        label.frame = NSRect(x: 0, y: 0, width: 200, height: 17)
        label.setNeedsDisplay()
    }
}

When the view loads, the label still has its original frame as set in interface builder, and not the newly set frame.

How does one programmatically move/resize the label?


回答1:


The autolayout system is the culprit here. When you set the frame, the autolayout system overrides that to re-establish the implicit constraints set in the storyboard.

Set the translatesAutoresizingMaskIntoConstraints property of the label to true. This tells the autolayout system that it should create a new set of autolayout constraints that satisfy the new frame you've set:

class ViewController: NSViewController {

    @IBOutlet var label: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        label.frame = NSRect(x: 0, y: 0, width: 200, height: 17)
        label.translatesAutoresizingMaskIntoConstraints = true
        label.setNeedsDisplay()
    }
}


来源:https://stackoverflow.com/questions/36732958/how-to-move-or-resize-an-nsview-by-setting-the-frame-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!