Создайте вспомогательный класс со следующим перечислением.
enum DeviceTraitStatus {
///IPAD and others: Width: Regular, Height: Regular
case wRhR
///Any IPHONE Portrait Width: Compact, Height: Regular
case wChR
///IPHONE Plus/Max Landscape Width: Regular, Height: Compact
case wRhC
///IPHONE landscape Width: Compact, Height: Compact
case wChC
static var current:DeviceTraitStatus{
switch (UIScreen.main.traitCollection.horizontalSizeClass, UIScreen.main.traitCollection.verticalSizeClass){
case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.regular):
return .wRhR
case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.regular):
return .wChR
case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.compact):
return .wRhC
case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.compact):
return .wChC
default:
return .wChR
}
}
}
Затем в методе делегата представления коллекции рассчитайте ширину соответственно.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return size(for: indexPath)
}
private func size(for indexPath: IndexPath) -> CGSize
{
let cell = Bundle.main.loadNibNamed("YourCollectionViewCell", owner: self, options: nil)?.first as! BoxSelectCollectionCell
cell.setNeedsLayout()
cell.layoutIfNeeded()
// Call the method to calculate the width
var width: CGFloat = 0
switch DeviceTraitStatus.current
{
case .wChR, .wChC: width = (collectionView.frame.size.width - padding/2).rounded(.down)
case .wRhR, .wRhC: width = (collectionView.frame.size.width/2 - padding/2).rounded(.down)
}
let height: CGFloat = 0
let targetSize = CGSize(width: width, height: height)
var size = cell.contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .defaultHigh, verticalFittingPriority: .fittingSizeLevel)
return size
}