Swift3 - 视觉格式约束崩溃

Swift3 - Visual Format Constraint crashing

我试图在 setupViews() 函数中使用视觉格式向 UICollectionViewCell 添加约束,但是每当我设置它们然后 运行 代码时,约束就会崩溃并且不会显示任何单元格。我收到以下错误:[LayoutConstraints] Unable to simultaneously satisfy constraints. 知道为什么会这样吗?

import UIKit

class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

override func viewDidLoad() {
    super.viewDidLoad()

    let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 50))
    self.view.addSubview(navBar)
    let navItem = UINavigationItem(title: "Drops")
    navItem.rightBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout))
    navBar.setItems([navItem], animated: false);

    collectionView?.backgroundColor = UIColor.white
    collectionView?.register(ImageCell.self, forCellWithReuseIdentifier: "cell-id")
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-id", for: indexPath)
    return cell
 }

func handleLogout() {
    let loginController = LoginController()
    present(loginController, animated: true, completion: nil)
  }
}

class ImageCell: UICollectionViewCell {
override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
 }

let smallCellView: UIImageView = {
    let imgview = UIImageView()
    imgview.translatesAutoresizingMaskIntoConstraints = false
    imgview.backgroundColor = UIColor.purple
    return imgview
 }()

let largeCellView: UIImageView = {
    let imgview = UIImageView()
    imgview.translatesAutoresizingMaskIntoConstraints = false
    imgview.backgroundColor = UIColor.green
    return imgview
 }()

func setupViews(){
    //addSubview(smallCellView)
    addSubview(largeCellView)

    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-50-[v1]-50-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v1" : largeCellView]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-50-[v1]-50-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v1" : largeCellView]))

 }

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
 }

}

您需要确保受限视图可以放入您的集合视图单元;即,图像视图周围 top/bottom/left/right 的边距为 50,您的集合视图单元格必须 至少 100 x 100(这将导致图像视图尺寸为 0)为了避免不可满足的约束错误。

如果您正在使用或实施 UICollectionViewDelegateFlowLayout sizeForItemAt

,您可以在情节提要中设置单元格大小