问题
In my project, my collectionview cell comprises of the entire screen width and height, i've set it to horizontal scrolling and for making it dynamic for all screensizes, i am using this method
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height: CGFloat = view.frame.size.height
let width: CGFloat = view.frame.size.width
return CGSize(width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
its working perfectly fine and takes care of the width and height of all screensizes but the problem is that on scrolling it is cutting of the screen from the right edge, I tried implementing it with a different method viewDidLayoutSubViews() of uicollectionviewdelegateflowlayout and it too takes cares of the screensizes but still has the same issue.The first image is the original cell how it should appear.
the next image is how it cuts off the right edge on scrolling. Initially i've static numberofIteminSection and keeps on cutting with every swipe. This one is the result of third or fourth swipe. I have enabled pagination so i dont know whats the issue here.
I have checked various posts on stack overflow regarding this but nothing seems to help and i am stuck. Any help would be appreciated a lot.
回答1:
You need to check the screen sizes in sizeForItemAtIndexPath like:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width
if screenWidth == 414{
return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50)
}else if screenWidth == 375{
return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50)
}else{
return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50 )
}
}
Add these functions also and customise according to your need:
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake( 5, 14, 5, 14)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 4;
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 4;
}
If this doesn't work then change UIEdgeInsetsMake in insetForSectionAt.
来源:https://stackoverflow.com/questions/44970452/collectionview-cell-dynamic-height-for-all-screensizes