在swift playgrounds中你如何设置一个viewcontroller并使用它?我之前用UIView完成了它,但是当处于不同的方向时UI被切断,所以我想尝试使用viewcontroller。
我已经let view = UIViewController()
了,但之后如何设置它以添加背景和内容呢?
答案 0 :(得分:16)
我发现要在swift playground中创建一个viewcontroller,你需要这个代码
import UIKit
import PlaygroundSupport
class ViewController:UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
}
}
let viewController = ViewController()
PlaygroundPage.current.liveView = viewController
PlaygroundPage.current.needsIndefiniteExecution = true
答案 1 :(得分:1)
Playground中具有多个子视图和自动布局的UIViewController示例。
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()