问题
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