I want to create an UIView as a container view or even more programmatically with the snapkit in Xcode 11.1, but it seems there is something wrong and I think Apple has changed UIView in Xcode 11.x (iOS 13.x) because I did it very easily in the previous versions of Xcode.
In SceneDelegate.swift (Apple has moved the window variable from AppDelegate.swift to SceneDelegate.swift)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
self.window = UIWindow(windowScene: windowScene)
self.window?.rootViewController = ViewController()
self.window?.makeKeyAndVisible()
}
}
}
ViewController.swift
class ViewController: UIViewController {
var containerView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.backgroundColor = .green
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .blue
setUpView()
}
func setUpView() {
self.view.backgroundColor = .blue
self.view.addSubview(containerView)
containerView.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view.snp.centerX)
make.centerY.equalTo(self.view.snp.centerY)
}
}
}
and the result:
To displaying a view using autolayout, you need to provide all W H X Y
satisfy the layout engine. But you missed width
and height
constraints.
Try this:
func setUpView() {
self.view.backgroundColor = .blue
self.view.addSubview(containerView)
containerView.snp.makeConstraints { (make) in
make.width.height.equalTo(100)
make.center.equalTo(self.view)
}
}