drootang
drootang

Reputation: 2503

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

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?

Upvotes: 0

Views: 2664

Answers (1)

drootang
drootang

Reputation: 2503

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()
    }
}

Upvotes: 3

Related Questions