0

我试图在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")
 }

}
4

1 回答 1

0

您需要确保受约束的视图可以适合的集合视图单元格;即图像视图的顶部/底部/左侧/右侧边距为 50,您的集合视图单元格必须至少为100 x 100(这将导致 0 大小的图像视图)以避免无法满足的约束错误.

如果您正在使用它,您可以在情节提要中设置单元格大小或实现UICollectionViewDelegateFlowLayout sizeForItemAt

于 2017-07-20T22:22:06.727 回答