Swift3 - 可视格式约束崩溃

时间:2017-07-20 20:56:26

标签: ios swift3 autolayout nslayoutconstraint visual-format-language

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

}

1 个答案:

答案 0 :(得分:0)

您需要确保受约束的视图能够适合内部您的集合视图单元格;即在图像视图周围的上/下/左/右边距为50时,您的集合视图单元格必须至少 100 x 100(这将导致0大小的图像视图)以避免不可满足的约束错误。

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

,您可以在故事板中设置单元格大小