NSMoron
NSMoron

Reputation: 151

How to center a view on the x axis using autolayout in Swift on MacOS?

Hi I'm just wanting to have a childView centered on the x axis of a NSViewController view using auto layout. I'm doing the following:

override func viewWillAppear()
{
    super.viewWillAppear()

    let childView = PagesView.init(frame: CGRect(x: 0, y: 0, width:100, height: 100))
    childView.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(childView)

    childView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
}

The childView doesn't even appear on the screen. When I remove the last line, then it gets positioned at 0,0. So something about that last line is causing it go haywire and I'm not sure why? I've used this exact same logic on iOS and it has worked fine.

Upvotes: 0

Views: 785

Answers (1)

folverap
folverap

Reputation: 126

All views should have constraints to define its location and size.

// This would create dimension constraints if your class cannot already infer them
childView.widthAnchor.constraint(equalToConstant: 100).isActive = true
childView.heightAnchor.constraint(equalToConstant: 100).isActive = true

You also need to specify a vertical anchor constraint so the view has enough information to be displayed.

childView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true

Upvotes: 2

Related Questions