NSView half of the window

I have an NSView and I want it to be half of the window.

This is what I have tried:
  • In storyboard I dragged a Custom View

  • I give it a Constraint of 0 in Top, Left and Bottom

How can I make it half of the screen even when the user changes the size of the screen?

Code Block
 @IBOutlet weak var nsView1: NSView!
nsView1.wantsLayer = true
nsView1.layer?.backgroundColor = NSColor.red.cgColor



Answered by Claude31 in 627537022

How can I make it half of the screen even when the user changes the size of the screen?

How do you change screen size ? Do you mean window size ?

Anyway, you have several ways:
  • create a second view, a few pixels wide ; make it transparent, no user interaction

  • put it below the first

  • create constraint to give it same height as the first one and distance of its top to the first bottom of 0

  • align it to the left of screen

You could also
  • create a constraint for the first view to the bottom of screen

  • create an IBOutlet for this constraints: bottomConstraint

  • in viewWillLayout, set bottomConstraint.constant to half height of screen

Accepted Answer

How can I make it half of the screen even when the user changes the size of the screen?

How do you change screen size ? Do you mean window size ?

Anyway, you have several ways:
  • create a second view, a few pixels wide ; make it transparent, no user interaction

  • put it below the first

  • create constraint to give it same height as the first one and distance of its top to the first bottom of 0

  • align it to the left of screen

You could also
  • create a constraint for the first view to the bottom of screen

  • create an IBOutlet for this constraints: bottomConstraint

  • in viewWillLayout, set bottomConstraint.constant to half height of screen

Sorry, I meant window size. (I do not see how to edit the question and correct that error)

Thank you for your answer.
NSView half of the window
 
 
Q