sakoaskoaso
sakoaskoaso

Reputation: 347

Swift: is it okay to add constraints to UICollectionview?

I have this class

class HomePage: UIViewController,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate

And in this class i have a lot of UIViews.One of which is tabView.Now i want to add my collectionView to the bottom of tabView,how can i do that? Here is my `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`

And constraints to 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

Upvotes: 0

Views: 1100

Answers (1)

Phyber
Phyber

Reputation: 1368

You can add the collectionView inside tabView and setup constraints:

collectionView.translatesAutoresizingMaskIntoConstraints = false
tabView.addSubview(collectionView)

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

.... And add other constraints

Or you can add it under tab view like so:

self.view.addSubview(collectionView)

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

__

BTW you can set tabView's width like so:

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

Upvotes: 2

Related Questions