Swift - Programmatically Change Constraints - swift

I am trying to 'show' & 'hide' a collection view by manipulating the constraints programmatically.
My app is written in code, no storyboards or #IBOutlets are being used.
The first time I press the button, the collection view appears correctly and as expected.
The second time I press the button, the collection view just stays in place and does not 'hide'.
The print statements within the openMenu code are confirming that each block of constraints is being called. ie: I get console messages for 'open' and 'closed'.
I don't have an issue with creating the collection view, it's just that setting the constraints programmatically does not close the menu.
My code is as follows...
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = false
view.backgroundColor = .white
view.addSubview(bgImageView)
view.addSubview(myListCV)
}
lazy var myListCV: UICollectionView = {
let myListLayout = UICollectionViewFlowLayout()
myListLayout.itemSize = CGSize(width: 200, height: 40)
myListLayout.minimumLineSpacing = 1
myListLayout.sectionHeadersPinToVisibleBounds = true
let myListView = UICollectionView(frame: .zero, collectionViewLayout: myListLayout)
myListView.translatesAutoresizingMaskIntoConstraints = false
myListView.delegate = self
myListView.dataSource = self
myListView.bounces = false
myListView.alwaysBounceVertical = false
myListView.showsVerticalScrollIndicator = true
myListView.backgroundColor = UIColor(r: 203, g: 203, b: 203)
return myListView
}()
var menuShowing = false
func openMenu() {
if (menuShowing) {
print("closed")
myListCV.leftAnchor.constraint(equalTo: view.rightAnchor).isActive = true
myListCV.topAnchor.constraint(equalTo: view.topAnchor, constant: 64).isActive = true
myListCV.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
myListCV.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
} else {
print("open")
myListCV.leftAnchor.constraint(equalTo: view.rightAnchor, constant: -200).isActive = true
myListCV.topAnchor.constraint(equalTo: view.topAnchor, constant: 64).isActive = true
myListCV.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
myListCV.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
menuShowing = !menuShowing
}

The problem with your above code is that you are continually setting constraints every time the user opens or closes the the section, so depending on how many times the user does this you'll end up with hundreds of constrains that just aren't needed.
What you should do is set the constraints for the default state, I'm assuming closed in this instance, and store the constraint you wish to change in a property. You can then simply adjust the constant of this constraint to show/hide your menu.
e.g.
private var myListCVLeftConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = false
view.backgroundColor = .white
view.addSubview(bgImageView)
self.configMyListCV()
}
lazy var myListCV: UICollectionView = {
let myListLayout = UICollectionViewFlowLayout()
myListLayout.itemSize = CGSize(width: 200, height: 40)
myListLayout.minimumLineSpacing = 1
myListLayout.sectionHeadersPinToVisibleBounds = true
let myListView = UICollectionView(frame: .zero, collectionViewLayout: myListLayout)
myListView.translatesAutoresizingMaskIntoConstraints = false
myListView.delegate = self
myListView.dataSource = self
myListView.bounces = false
myListView.alwaysBounceVertical = false
myListView.showsVerticalScrollIndicator = true
myListView.backgroundColor = UIColor(r: 203, g: 203, b: 203)
return myListView
}()
var menuShowing = false
private func configMyListCV() -> Void {
view.addSubview(myListCV)
self.myListCV.topAnchor.constraint(equalTo: view.topAnchor, constant: 64).isActive = true
self.myListCV.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
self.myListCV.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
self.myListCVLeftConstraint = myListCV.leftAnchor.constraint(equalTo: view.rightAnchor)
self.myListCVLeftConstraint.isActive = true
}
func openMenu() {
if (menuShowing) {
self.myListCVLeftConstraint?.constant = 0.0
} else {
self.myListCVLeftConstraint?.constant = -200.0
}
menuShowing = !menuShowing
}
This will work well for this simple user case; however if you do anything more in depth in the future I'd suggest setting multiple constraints on the view and simply disable/enable the required ones as needed.

Related

How to make long text label, which lives in UI View, to multiple lines in Swift?

I'm trying to make a long text label, which lives inside of UI View, to multiple lines. I was searching for a solution for 2 hours, but I couldn't solve it, so I want to ask for some help. Here is the image of what I get now.
This is the View Hierarchy debugger.
In a table view cell, I put the repository name which I got from Github. In the third cell in the image, I want to make the repo name to two lines, since it's long. I saw this StackOverflow question, which sounds similar to my current problem and implemented in my code, but it didn't work.
Here is my code. It's too long but the point is, I have declared label.numberOfLines = 0 and label.adjustsFontSizeToFitWidth = true, and I tried to make my label convertible to multiple lines, but it didn't work. Could anyone please point me at what I'm doing wrong here?
import UIKit
class RepositoryCell: UITableViewCell {
//MARK: - Properties
let userImageView: UIImageView = {
let img = UIImageView()
img.contentMode = .scaleAspectFit
img.clipsToBounds = true
img.backgroundColor = .black
return img
}()
let containerView: UIView = {
let view = UIView()
view.clipsToBounds = true
view.backgroundColor = .systemPink
return view
}()
let userNameLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.font = UIFont.boldSystemFont(ofSize: 20)
label.numberOfLines = 0
label.adjustsFontSizeToFitWidth = true
return label
}()
let repositoryNameLabel: UILabel = {
let label = UILabel()
label.textColor = .gray
label.font = UIFont.systemFont(ofSize: 14)
label.numberOfLines = 0
label.adjustsFontSizeToFitWidth = true
return label
}()
let starNumLabel: UILabel = {
let label = UILabel()
label.textColor = .systemPink
label.font = UIFont.systemFont(ofSize: 14)
label.backgroundColor = .black
return label
}()
//MARK: - Init
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(userImageView)
containerView.addSubview(userNameLabel)
containerView.addSubview(repositoryNameLabel)
addSubview(containerView)
addSubview(starNumLabel)
configureUserNameLabel()
configureRepositoryNameLabel()
configureViewConstraints()
}
override func layoutSubviews() {
super.layoutSubviews()
userImageView.layer.cornerRadius = userImageView.frame.height / 2
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Helper functions
func configureCellView(repository: Repository) {
userImageView.image = UIImage(named: "001")
userNameLabel.text = repository.userName
repositoryNameLabel.text = repository.repositoryName
starNumLabel.text = "⭐️\(String(describing: repository.starNum))"
}
func configureUserNameLabel() {
userNameLabel.numberOfLines = 0
userNameLabel.adjustsFontSizeToFitWidth = true
}
func configureRepositoryNameLabel() {
repositoryNameLabel.numberOfLines = 0
repositoryNameLabel.adjustsFontSizeToFitWidth = true
}
func configureViewConstraints() {
setUserImageConstraints()
setContainerViewConstraints()
setUserNameLabelConstraints()
setRepositoryNameLabel()
setStarNumLabel()
}
func setUserImageConstraints() {
userImageView.translatesAutoresizingMaskIntoConstraints = false
userImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
userImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
userImageView.heightAnchor.constraint(equalToConstant: 70).isActive = true
userImageView.widthAnchor.constraint(equalTo: userImageView.heightAnchor, multiplier: 1).isActive = true
}
func setContainerViewConstraints() {
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
containerView.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
containerView.leadingAnchor.constraint(equalTo: userImageView.trailingAnchor, constant: 10).isActive = true
containerView.trailingAnchor.constraint(equalTo: starNumLabel.leadingAnchor, constant: -10).isActive = true
}
func setUserNameLabelConstraints() {
userNameLabel.translatesAutoresizingMaskIntoConstraints = false
userNameLabel.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
userNameLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
// userNameLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
}
func setRepositoryNameLabel() {
repositoryNameLabel.translatesAutoresizingMaskIntoConstraints = false
repositoryNameLabel.topAnchor.constraint(equalTo: userNameLabel.bottomAnchor).isActive = true
repositoryNameLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
// repositoryNameLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
// this doesn't work...
// repositoryNameLabel.trailingAnchor.constraint(greaterThanOrEqualTo: containerView.leadingAnchor, constant: 5).isActive = true
}
func setStarNumLabel() {
starNumLabel.translatesAutoresizingMaskIntoConstraints = false
starNumLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
starNumLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
}
}
My guess is the trailing constraints of your label is not set properly.
You can use the View Hierarchy debugger in Xcode to have a clear view of the size your view actually has at runtime.
If the trailing anchor is not set, wrapping text isn't possible as it doesn't reach the "end" of the view.

Thread 1: signal SIGABRT when my code runs

Total Swift newbie here. I am trying to make two containers that span half of the view.heightAnchor.constraint with one function createhalfcontainer in order to make things neater. Whenever I run my code, I get the signal SIGABRT and despite extensive code review I can't seem to find out why.
class ViewController: UIViewController {
let iv = {() -> UIImageView in
let imageview = UIImageView(image: #imageLiteral(resourceName: "google"))
imageview.contentMode = UIViewContentMode.scaleAspectFit
return imageview
}()
let tv = {() -> UITextView in
let textview = UITextView()
textview.text = "I am going to work here soon."
textview.font = UIFont.boldSystemFont(ofSize: 16)
textview.textAlignment = NSTextAlignment.center
textview.isEditable = false
return textview
}()
func createhalfcontainer(within: UIView, direction:String, view: UIView)-> UIView{
let container = UIView()
container.translatesAutoresizingMaskIntoConstraints = false
within.translatesAutoresizingMaskIntoConstraints = false
container.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 0.5).isActive = true
container.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
container.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
if direction == "up" {
container.topAnchor.constraint(equalTo:view.topAnchor).isActive = true
within.topAnchor.constraint(equalTo: container.topAnchor, constant: 100).isActive = true}
else {container.bottomAnchor.constraint(equalTo:view.bottomAnchor).isActive = true
within.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: 100).isActive = true}
within.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
within.trailingAnchor.constraint(equalTo: container.trailingAnchor).isActive = true
container.addSubview(within)
return container
}
override func viewDidLoad() {
super.viewDidLoad() //This instantiates the view object
let uppercontainer = self.createhalfcontainer(within: iv, direction: "up", view:view)
let bottomcontainer = self.createhalfcontainer(within: tv, direction: "bottom",view:view)
view.addSubview(uppercontainer)
view.addSubview(bottomcontainer)
}
}

Scroll View is moving horizontally and not vertically

I have created a scroll view and I have tried many different methods as you can see below, however I always get the same outcome where the scroll view moves horizontally. I want it to move vertically, but it is not. Also, the text view shows the entire message in one line and does not use multiple lines as was happening before I added the scroll view.
import UIKit
import SafariServices
class MainView: UIViewController {
let transition = MainDropMenuAnimation()
let scrollView = UIScrollView()
let scrollViewView = UIView()
let factView = QuickFact()
let socialMediaSV = SocialMediaSV()
let logo = UIImageView()
let aboutUs = UITextView()
let dropMenuButton = UIButton(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "HomeBackground"))
addQuickFactView()
setupScrollView()
setupNavBar()
}
func setupNavBar() {
navigationItem.title = "Home"
navigationController?.navigationBar.barTintColor = .clear
dropMenuButton.setImage(#imageLiteral(resourceName: "dropMenuButton"), for: .normal)
dropMenuButton.addTarget(self, action: #selector(handleDropMenu), for: .touchUpInside)
dropMenuButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
dropMenuButton.widthAnchor.constraint(equalTo: dropMenuButton.heightAnchor).isActive = true
let leftButton = UIBarButtonItem(customView: dropMenuButton)
self.navigationItem.leftBarButtonItem = leftButton
}
#objc func handleDropMenu() {
let dropMenu = DropViewContainer()
dropMenu.modalPresentationStyle = .overCurrentContext
dropMenu.transitioningDelegate = self
present(dropMenu, animated: true)
}
func addQuickFactView() {
addChild(factView)
view.addSubview(factView.view)
factView.didMove(toParent: self)
factView.view.translatesAutoresizingMaskIntoConstraints = false
factView.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
factView.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
factView.view.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
factView.view.heightAnchor.constraint(equalToConstant: 200).isActive = true
}
func setupScrollView() {
setupView()
scrollView.contentSize.height = 3000
view.addSubview(scrollView)
positionScrollView()
}
func positionScrollView() {
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: factView.view.bottomAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func setupView() {
setupLogo()
setupAboutUs()
setupSocialMediaSV()
scrollView.addSubview(scrollViewView)
positionView()
}
func positionView() {
scrollViewView.translatesAutoresizingMaskIntoConstraints = false
scrollViewView.rightAnchor.constraint(equalTo: scrollView.rightAnchor).isActive = true
scrollViewView.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
scrollViewView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
scrollViewView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
}
func setupLogo() {
logo.image = #imageLiteral(resourceName: "Logo")
scrollViewView.addSubview(logo)
positionLogo()
}
func positionLogo() {
logo.translatesAutoresizingMaskIntoConstraints = false
logo.widthAnchor.constraint(equalToConstant: 200).isActive = true
logo.heightAnchor.constraint(equalToConstant: 200).isActive = true
logo.centerXAnchor.constraint(equalTo: scrollViewView.centerXAnchor).isActive = true
logo.topAnchor.constraint(equalTo: scrollViewView.topAnchor, constant: 20).isActive = true
}
func setupAboutUs() {
let aboutUsText = (NSMutableAttributedString(string: "About Us\n", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 25)]))
aboutUsText.append(NSMutableAttributedString(string: "At Cleaner Together, we are commited to promoting recycling, reusing, and reducing (and of course composting), while spreading sanitization and cleanliness around the world. At the moment, we are just encouraging proper waste disposal, however with proper funding we have many projects we hope to accomplish.", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: UIColor.black]))
aboutUs.attributedText = aboutUsText
aboutUs.textColor = .black
aboutUs.textAlignment = .left
aboutUs.isScrollEnabled = false
aboutUs.isEditable = false
aboutUs.backgroundColor = .init(white: 1.0, alpha: 0.5)
aboutUs.layer.cornerRadius = 20
scrollViewView.addSubview(aboutUs)
positionAboutUs()
}
func positionAboutUs() {
aboutUs.translatesAutoresizingMaskIntoConstraints = false
aboutUs.rightAnchor.constraint(equalTo: scrollViewView.rightAnchor, constant: -20).isActive = true
aboutUs.leftAnchor.constraint(equalTo: scrollViewView.leftAnchor, constant: 20).isActive = true
aboutUs.heightAnchor.constraint(equalToConstant: 200).isActive = true
aboutUs.topAnchor.constraint(equalTo: logo.bottomAnchor, constant: 20).isActive = true
}
func setupSocialMediaSV() {
addChild(socialMediaSV)
scrollViewView.addSubview(socialMediaSV.view)
socialMediaSV.didMove(toParent: self)
socialMediaSV.view.translatesAutoresizingMaskIntoConstraints = false
socialMediaSV.view.centerXAnchor.constraint(equalTo: scrollViewView.centerXAnchor).isActive = true
socialMediaSV.view.widthAnchor.constraint(equalToConstant: 240).isActive = true
socialMediaSV.view.topAnchor.constraint(equalTo: aboutUs.bottomAnchor, constant: 20).isActive = true
socialMediaSV.view.heightAnchor.constraint(equalToConstant: 40).isActive = true
}
}
extension MainView: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.isPresenting = true
return transition
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.isPresenting = false
return transition
}
}
You should check your constraints and make sure that your scroll view has correct contentSize.
Make scrollViewView left and right anchors also equalTo viewController's view. In func positionView()

Scroll view not scrolling horizontal

I have a custom view, i set it in parent like:
func setup(){
view.backgroundColor = .gray
view.addSubview(chartView)
chartView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
chartView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
chartView.topAnchor.constraint(equalTo: view.topAnchor, constant: statusAndNavigationBarHeight).isActive = true
chartView.heightAnchor.constraint(equalToConstant: Dimensions.chartHeight.value).isActive = true
}
Then in that view i tried to set up a scroll:
scroll = UIScrollView.init(frame: CGRect(x: 0.0, y: 0.0, width: scrollWidth(), // print 728.0
height: Double(Dimensions.chartHeight.value))) // print 400.0
scroll.isScrollEnabled = true
scroll.showsHorizontalScrollIndicator = true
addSubview(scroll)
}
And thats all, when i launch app i can't drag and scroll horizontally, in debug editor i can't see that it is scroll view here lying with large width.
The scrollView doesn't scroll with it's size , it needs a content that define it's content size for example
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let chartView = UIView()
chartView.translatesAutoresizingMaskIntoConstraints = false
chartView.backgroundColor = .red
view.backgroundColor = .gray
view.addSubview(chartView)
chartView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
chartView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
chartView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
chartView.heightAnchor.constraint(equalToConstant:200).isActive = true
let scroll = UIScrollView(frame: CGRect(x: 0.0,
y: 0.0,
width: UIScreen.main.bounds.size.width, // print 728.0
height: 200.0))
scroll.isScrollEnabled = true
scroll.showsHorizontalScrollIndicator = true
chartView.addSubview(scroll)
let www = UIView()
www.backgroundColor = .green
www.translatesAutoresizingMaskIntoConstraints = false
scroll.addSubview(www)
www.leftAnchor.constraint(equalTo: scroll.leftAnchor).isActive = true
www.rightAnchor.constraint(equalTo: scroll.rightAnchor).isActive = true
www.topAnchor.constraint(equalTo: scroll.topAnchor).isActive = true
www.bottomAnchor.constraint(equalTo: scroll.bottomAnchor).isActive = true
www.heightAnchor.constraint(equalToConstant:200).isActive = true
www.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier:2.0).isActive = true
scroll.addSubview(www)
}
}

Adding constraints programmatically leads to unexpected behavior

I'm playing around with constraints, trying to learn how they work and to try and learn how to build a UI without IB, and I'm not getting the results I anticipated. In the code below, if I comment out the constraints at the end, I can see the purple view. If I uncomment them, all I get is an empty window where I would expect the view to be pinned to the left, topped right edges of the main view.
I've also tried doing a similar thing with the centerX and centerY properties to try and center the view in the middle of the window, again I get an empty window when those are activated.
Any help appreciated!
import Cocoa
class ViewController : NSViewController {
override func loadView() {
// NSMakeRect parameters do nothing?
let view = NSView(frame: NSMakeRect(0,0,400,2000))
view.wantsLayer = true
view.layer?.borderWidth = 5
view.layer?.borderColor = NSColor.gray.cgColor
self.view = view
}
override func viewWillAppear() {
super.viewWillAppear()
// Do any additional setup after loading the view.
createMasterView()
}
func makeView() -> NSView {
let view = NSView()
view.translatesAutoresizingMaskIntoConstraints = false
view.setFrameSize(NSSize(width: 600, height: 100))
view.wantsLayer = true
view.heightAnchor.constraint(equalToConstant: 1000)
return view
}
func createMasterView() {
let mainView = self.view
let headerView = makeView()
headerView.layer?.backgroundColor = NSColor.purple.cgColor
headerView.layer?.borderWidth = 5
headerView.layer?.borderColor = CGColor.black
mainView.translatesAutoresizingMaskIntoConstraints = false
mainView.addSubview(headerView)
headerView.topAnchor.constraint(equalTo: mainView.topAnchor).isActive = true
headerView.leadingAnchor.constraint(equalTo: mainView.leadingAnchor).isActive = true
headerView.trailingAnchor.constraint(equalTo: mainView.trailingAnchor).isActive = true
}
}
Edit: I'm also including my AppDelegate code below. I'm still very new to all this so the code is stuff I've cobbled together from various tutorials.
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var windowController: NSWindowController!
var window: NSWindow!
var windowTitle = "Test App"
var customBGColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)
func applicationDidFinishLaunching(_ aNotification: Notification) {
createMainWindow()
}
func createMainWindow() {
window = NSWindow()
// window.alphaValue = 0.5
window.backgroundColor = customBGColor
window.title = windowTitle
window.styleMask = NSWindow.StyleMask(rawValue: 0xf)
window.backingType = .buffered
window.contentViewController = ViewController()
window.setFrame(NSRect(x: 700, y: 200, width: 1920, height: 1080), display: false)
windowController = NSWindowController()
windowController.contentViewController = window.contentViewController
windowController.window = window
windowController.showWindow(self)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
view.setFrameSize(NSSize(width: 600, height: 100))
You are overriding the height shortly afterwards with the heightAnchor.
Try setting width as well with an anchor
With auto layout, you don't touch the frame property of the view. When working programmatically, however, you have to with the view itself, but after that, all subviews can be sized and positioned using constraints. For clarity, I got rid of makeView():
func createMasterView() {
let headerView = NSView() // instantiate
headerView.layer?.backgroundColor = NSColor.purple.cgColor // style
headerView.layer?.borderWidth = 5
headerView.layer?.borderColor = CGColor.black
headerView.translatesAutoresizingMaskIntoConstraints = false // disable mask translating
view.addSubview(headerView) // add as a subview
// then configure constraints
// one possible setup
headerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
headerView.heightAnchor.constraint(equalToConstant: 100).isActive = true
// another possible setup
headerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
headerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
headerView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5).isActive = true
// another possible setup
headerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
headerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
headerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -50).isActive = true
headerView.heightAnchor.constraint(equalTo: view.heightAnchor, constant: -50).isActive = true
}