我想使用Xcode 11.1中的snapkit创建UIView作为容器视图,或者甚至以编程方式创建UIView,但是似乎出了点问题,我认为Apple已更改Xcode 11.x(iOS 13.x)中的UIView,因为我在以前版本的Xcode中非常容易做到这一点。
在SceneDelegate.swift中(Apple已将窗口变量从AppDelegate.swift移至SceneDelegate.swift中)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
let viewController = ViewController()
if let windowScene = scene as? UIWindowScene {
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)
}
}
}
和结果:
答案 0 :(得分:2)
要使用自动布局显示视图,您需要提供所有W H X Y
个满足布局引擎要求的视图。但是您错过了width
和height
约束。
尝试一下:
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)
}
}
答案 1 :(得分:-1)
您需要设置容器视图的高度和宽度。
containerView.heightAnchor.constraint(equalToConstant: 100).isActive = true
containerView.widthAnchor.constraint(equalToConstant: 100).isActive = true