CameraDev
CameraDev

Reputation: 33

How to set UICollectionView width programmatically

I would like to set the width of an UICollectionView programmatically. I have tried to modify collectionView.frame and .bounds without success.

class CenterCellCollectionViewFlowLayout: UICollectionViewFlowLayout {
 override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
   if let cv = self.collectionView {
     let cvBounds = cv.bounds
     let width = cvBounds.size.width //this is always 600, it should be 320
   }
 }
 return super.targetContentOffsetForProposedContentOffset(proposedContentOffset)
}

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
 @IBOutlet weak var collectionView: UICollectionView!
 override func viewDidLoad() {
   super.viewDidLoad()
   collectionView.frame = CGRectMake(collectionView.frame.origin.x, collectionView.frame.origin.y, self.view.frame.width, collectionView.frame.height)
   collectionView.bounds = CGRectMake(collectionView.bounds.origin.x, collectionView.bounds.origin.y, self.view.frame.width, collectionView.bounds.height)
   let width = collectionView.bounds.width //this is 320
   collectionView.reloadData()
 }
}

Storyboard

Upvotes: 1

Views: 1546

Answers (2)

bsmith11
bsmith11

Reputation: 296

You should use NSLayoutConstraints: https://developer.apple.com/library/ios/documentation/AppKit/Reference/NSLayoutConstraint_Class/

The reason you are getting an incorrect width is because you are setting it in viewDidLoad(). self.view has not been laid out at this point in the lifecycle. viewWillLayoutSubviews() is the lifecycle method you want to use, as it is called after self.view has been laid out and allows you to manually adjust any subview's (your UICollectionView) layout.

Upvotes: 1

Rufel
Rufel

Reputation: 2660

You are using self.view.frame.width when building your Rect, which means you are getting the width of your ViewController's view. This ViewController is probably taking the full screen, which means 320 pixels on an iPhone 4 or iPhone 5.

Upvotes: 0

Related Questions