theflarenet theflarenet - 2 years ago 172
Swift Question

UICollectionView width programatically conflicting with storyboard initialization

I've created a UICollectionView through the storyboard and temporarily positioned it in the view; however, I'd like to overwrite the positions programmatically on launch rather than using the storyboard configuration.

enter image description here

I thought

was the right location to place make this change?

Swift 2 Code:

override func viewDidLoad() {

collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
collectionView.backgroundColor = UIColor(white:1, alpha:0.0)

// Doesn't stretch the width to the device's width on launch. :-(
collectionView.frame.size = CGSize(width: UIScreen.mainScreen().bounds.width, height: 200)

Answer Source

If you are setting constraints and then want to change height or width then you should take outlet of that height or width and increament it's constant value. just ctrl+drag from width constraint to class and make outlate and then increment that outlate's contant property in viewdidload.

for example,

@IBOutlet weak var heightConstraint: NSLayoutConstraint!

self.heightConstraint.constant = 200

And second thing if you want to keep your collectionview's height equal with device then there is no need to set programatically. autolayout manage it if you set proper constraint. so main point is use autolayout at evrywhere or not at all. dont mix both autolayout and then set frame programatically.

hope this will help :) enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download