Swift:可以向UICollectionview添加约束吗?

时间:2017-07-31 07:55:03

标签: ios swift

我有这个班级

class HomePage: UIViewController,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate

在本课程中,我有很多UIViews.One是tabView。现在我想将collectionView添加到tabView的底部,我该怎么做?这是我的`collectionView

    var flowLayout = UICollectionViewFlowLayout()

    let collectionView = UICollectionView(frame: CGRect(x:0,y:500,width:self.view.frame.size.width,height:100   ), collectionViewLayout: flowLayout)
    collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.backgroundColor = .red`

tabView

的约束
    tabView.topAnchor.constraint(equalTo: profileInfWrapper.bottomAnchor).isActive = true
    tabView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    tabView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.size.width/4).isActive = true
    tabView.heightAnchor.constraint(equalToConstant: 80).isActive = true

1 个答案:

答案 0 :(得分:2)

您可以在tabView和设置约束中添加collectionView:

collectionView.translatesAutoresizingMaskIntoConstraints = false
tabView.addSubview(collectionView)

collectionView.topAnchor.constraint(equalTo: tabView.topAnchor, constant: 20).isActive = true

....并添加其他约束

或者您可以在标签视图下添加它,如下所示:

self.view.addSubview(collectionView)

collectionView.topAnchor.constraint(equalTo: tabView.bottomAnchor, constant: 20).isActive = true

__

顺便说一句,你可以这样设置tabView的宽度:

tabView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.25).isActive = true