How to setup ViewController in Playgrounds?

后端 未结 2 1318
南笙
南笙 2021-02-06 08:01

In swift playgrounds how do you setup a viewcontroller and use it? I\'ve done it with a UIView before but the UI gets cut when in a difference orientation so I want to try use a

2条回答
  •  自闭症患者
    2021-02-06 08:48

    Example of UIViewController in Playground with multiple Subviews and Auto layout.

    import UIKit
    import PlaygroundSupport
    
    class ViewController : UIViewController {
    
        var yellowView: UIView!
        var redView: UIView!
    
        override func loadView() {
    
            // UI
    
            let view = UIView()
            view.backgroundColor = .white
    
            yellowView = UIView()
            yellowView.backgroundColor = .yellow
            view.addSubview(yellowView)
    
            redView = UIView()
            redView.backgroundColor = .red
            view.addSubview(redView)
    
            // Layout
            redView.translatesAutoresizingMaskIntoConstraints = false
            yellowView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                yellowView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
                yellowView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
                yellowView.widthAnchor.constraint(equalToConstant: 80),
                yellowView.heightAnchor.constraint(equalToConstant: 80),
    
                redView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
                redView.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -20),
                redView.widthAnchor.constraint(equalToConstant: 80),
                redView.heightAnchor.constraint(equalToConstant: 80)
                ])
    
            self.view = view
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    }
    
    PlaygroundPage.current.liveView = ViewController()
    

提交回复
热议问题