How to setup ViewController in Playgrounds?

血红的双手。 提交于 2019-12-09 13:48:26

问题


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 viewcontroller. I've got let view = UIViewController() but after that how do I set it up to add a background and stuff on it?


回答1:


I found that to create a viewcontroller in swift playgrounds you need this code

import UIKit
import PlaygroundSupport

class ViewController:UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()

    }

}

let viewController = ViewController()
PlaygroundPage.current.liveView = viewController
PlaygroundPage.current.needsIndefiniteExecution = true



回答2:


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()



来源:https://stackoverflow.com/questions/43160615/how-to-setup-viewcontroller-in-playgrounds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!