简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM