【问题标题】:Creating UIViews Programmatically doesn't work in Xcode 11.1以编程方式创建 UIView 在 Xcode 11.1 中不起作用
【发布时间】:2019-11-02 22:02:23
【问题描述】:

我想在 Xcode 11.1 中使用 snapkit 以编程方式创建 UIView 作为容器视图,但似乎有问题,我认为 Apple 在 Xcode 11.x (iOS 13.x) 中更改了 UIView,因为我在以前的 Xcode 版本中很容易做到。

在 SceneDelegate.swift 中(Apple 已将 window 变量从 AppDelegate.swift 移至 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)
        }
    }
}

结果:

【问题讨论】:

    标签: ios swift ios13 xcode11 snapkit


    【解决方案1】:

    要使用自动布局显示视图,您需要提供所有满足布局引擎的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)
        }
    }
    

    【讨论】:

      【解决方案2】:

      您需要设置容器视图的高度和宽度。

      containerView.heightAnchor.constraint(equalToConstant: 100).isActive = true
      containerView.widthAnchor.constraint(equalToConstant: 100).isActive = true
      

      【讨论】:

        猜你喜欢
        • 2018-08-22
        • 2018-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多