collectionViewCells到collectionView位置x:0,y:0

时间:2017-05-13 23:04:46

标签: swift uicollectionview uicollectionviewcell nslayoutconstraint uicollectionviewlayout

我遇到了collectionViewCells的一些布局问题。我是以编程方式应用布局约束,而UICollectionViewCells没有被固定到我的collectionView中的0,0位置。参见附件截图以供参考。提前谢谢!

class CurrentUserPlaceDetailsVC: UIViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupMenuBar()
    }

    let menuBar: MenuBar = {
        let mb = MenuBar()
        return mb
    }()

    private func setupMenuBar() {
        view.addSubview(menuBar)
        view.addConstraintsWithFormat("H:|[v0]|", views: menuBar)
        view.addConstraintsWithFormat("V:|-64-[v0(150)]", views: menuBar)

    }
    var placesTableVC: PlacesTableVC?
}

class MenuBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.green
        cv.dataSource = self
        cv.delegate = self
        return cv
    }()

    let cellId = "cellId"

    override init(frame: CGRect) {
        super.init(frame: frame)


        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)

        addSubview(collectionView)
        addConstraintsWithFormat("H:|[v0]|", views: collectionView)
        addConstraintsWithFormat("V:|[v0]|", views: collectionView)

    }

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

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

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

}


extension UIView {

    func addConstraintsWithFormat(_ format: String, views: UIView...) {
        var viewsDictionary = [String: UIView]()
        for (index, view) in views.enumerated() {
            let key = "v\(index)"
            view.translatesAutoresizingMaskIntoConstraints = false
            viewsDictionary[key] = view
        }

        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
    }

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要设置用于初始化minimumLineSpacing的{​​{1}}实例的headerReferenceSizesectionInset和/或UICollectionViewFlowLayout。您还可以设置UICollectionView的{​​{1}}。

试试这个:

contentInset