另一个collectionview内的collection view单元格的约束

时间:2018-12-30 16:11:43

标签: ios swift constraints nslayoutconstraint

我为UICollectionView创建了自定义类。我想将另一个“集合”视图放入第一类的单元格中。

import UIKit

class ModeCell: UICollectionViewCell {

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


    let modeCollection : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .cyan
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        return collectionView
    }()

    func setupView(){
        backgroundColor = .red

        addSubview(modeCollection)
                addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[v0(180)]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": modeCollection]))

                addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-25-[v0(180)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": modeCollection]))

                addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-30-[v0(160)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": modeCollection]))

                addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-95-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": modeCollection]))

    }

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

此代码可以正常工作,但是我想知道是否有可能在我在其他项目中使用约束时使用约束:

modeCollection.centerXAnchor.constraint(equalTo:.centerXAnchor).isActive = true modeCollection.bottomAnchor.constraint(equalTo:view.bottomAnchor).isActive = true modeCollection.widthAnchor.constraint(equalTo:view.widthAnchor).isActive = true modeCollection.heightAnchor.constraint(equalToConstant:49).isActive = true

问题是我的新自定义类中没有“视图”,并且我没有什么可引用的...

1 个答案:

答案 0 :(得分:0)

您没有为<body>创建约束,而是为view本身(在您的情况下为self)上创建约束UICollectionViewCell