Search code examples
iosswiftswift-playground

Center a view inside viewcontroller in iOS Playground app


I'm currently building a swift playground book. Is it possible to center a view inside a view controller while running on an iPad ?

Here's my loadView function of my view controller:

override public func loadView() {
    let view = UIView()
    view.backgroundColor = .white
    view.frame = CGRect(x: 0, y: 0, width: 375, height: 667)
    self.view = view

    let frame = CGRect(x: 0, y: 0, width: 375, height: 375)
    let newView = UIView(frame: frame)
    view.addSubview(newView)
}

How can I center the newViewin the view of the view controller?

Thanks !


Solution

  • You can try to do it using Autolayout:

    let frame = CGRect(x: 0, y: 0, width: 375, height: 375)
    let newView = UIView(frame: frame)
    view.addSubview(newView)
    newView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        newView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        newView.leftAnchor.constraint(equalTo: view.leftAnchor),
        newView.rightAnchor.constraint(equalTo: view.rightAnchor),
        newView.widthAnchor.constraint(equalTo: newView.heightAnchor),
    ])
    newView.backgroundColor = UIColor.red
    

    UPDATE

    Playground code:

    import UIKit
    import PlaygroundSupport
    
    class MyViewController : UIViewController {
        override func loadView() {
            let view = UIView()
            view.backgroundColor = .red
            view.frame = CGRect(x: 0, y: 0, width: 375, height: 667)
            self.view = view
    
            let frame = CGRect(x: 0, y: 0, width: 375, height: 375)
            let newView = UIView(frame: frame)
            newView.backgroundColor = .blue
            view.addSubview(newView)
    
            newView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                newView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
                newView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
                // need to define its size too
                newView.heightAnchor.constraint(equalToConstant: 375),
                newView.widthAnchor.constraint(equalTo: view.heightAnchor),
                ])
        }
    }
    // Present the view controller in the Live View window
    PlaygroundPage.current.liveView = MyViewController()