Reputation: 149
I have a collection view controller and I set up it like this:
class r : UICollectionViewCell {
override var bounds: CGRect {
didSet {
contentView.frame = bounds
}
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "1", for: indexPath) as? r
cell.backgroundColor = UIColor.red
return cell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
I want that the cell's width is equals to screen's width , for this reason in storyboard I edited cell's width:
but I have a problem :
if I execute it on iPhone 6 simulator I get this(and this is what I want to get on all devices) :
but If execute on iPad Pro I get this :
And I don't understand why. Can you help me?
P.S I don't want to use tableview for some reasons
Upvotes: 0
Views: 1557
Reputation: 400
If u use Constraint so first of all your cell to apply equal width constraint and also storyboard in you should check collection view setting in inspect editor for horizontal and vertical.proper all setting..
Upvotes: 1
Reputation: 607
In iOS 10 there is a minor difference in function prototype: Here is Swift3.0 Delegate method for sizeAtItemAtIndexPath:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let screenRect: CGRect = UIScreen.main.bounds
let screenWidth: CGFloat = screenRect.size.width
let screencellHeight: CGFloat = screenRect.size.height
let cellWidth: CGFloat = screenWidth / CGFloat(2)
let cellHeight:CGFloat = screencellHeight / CGFloat(10.0)
let size: CGSize = CGSize(width: cellWidth, height: cellHeight)
return size
}
Upvotes: 1
Reputation: 1486
I think you are using constraints. If yes, then all you have to do is just fix the width of your cell in constraints.
Unless you didn't change that. No matter where you have set the width ind delegates.It will remain same.
Upvotes: 0
Reputation: 19602
I assume you have set a fixed width for your cell somewhere. Maybe as constraint. Set it dynamically:
UICollectionViewDelegateFlowLayout
and override:
@objc(collectionView:layout:sizeForItemAtIndexPath:)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let desiredNumberOfCollumns: CGFloat = 1
let width = collectionView.frame.width / desiredNumberOfCollumns
let height = 100 // your desired height
return CGSize(width: width, height: hight)
}
Upvotes: 0