I’m trying to create a custom calendar in my app and I added the following code.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width/7, height: 36)
}
But in different iPad devices, the weekdays show more than 7 & and some iPad show 5 days of the week. It's changing the cell size depending on the screen size. But I want to add & days for all iPad screen widths. Then I tried the following
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if UIDevice().userInterfaceIdiom == .pad
{
if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad &&
(UIScreen.main.bounds.size.height == 1366 || UIScreen.main.bounds.size.width == 1366))
{
print("iPad Pro : 12.9 inch")
return CGSize(width: collectionView.frame.width/7 + 20, height: 36)
}
else if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad &&
(UIScreen.main.bounds.size.height == 1024 || UIScreen.main.bounds.size.width == 1024))
{
print("iPad 2 || iPad Pro : 9.7 inch || iPad Air/iPad Air 2 || iPad Retina ")
return CGSize(width: collectionView.frame.width/7 - 5, height: 36)
}
else if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad &&
(UIScreen.main.bounds.size.height == 1180 || UIScreen.main.bounds.size.width == 1180))
{
print("iPad Air 4th gen")
return CGSize(width: collectionView.frame.width/7 + 5, height: 45)
}
else if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad &&
(UIScreen.main.bounds.size.height == 1194 || UIScreen.main.bounds.size.width == 1194))
{
print("iPad Pro 11")
return CGSize(width: collectionView.frame.width/7 + 5, height: 45)
}
else if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad &&
(UIScreen.main.bounds.size.height == 1112 || UIScreen.main.bounds.size.width == 1112))
{
print("iPad Air 3")
return CGSize(width: collectionView.frame.width/7, height: 45)
}
else
{
print("iPad 3")
return CGSize(width: collectionView.frame.width/7, height: 45)
}
}
return CGSize(width: collectionView.frame.width/7, height: 45)
}
For using this most of the iPad devices are getting exactly 7 days cell. But some devices (iPad 5th, 6th, 7th generation) with 1024 screen width still showing 6 days a week. I tried with the simulator.
I got the perfect solution with the following code.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: (self.contentView.frame.width - 173)/7, height: 45) }