[英]How do I apply aspect ratio constraints to a custom UICollectionViewCell programmatically?
我正在尝试创建一个显示相册封面的网格样式视图。 我想要每行3张专辑封面。 棘手的部分是根据所使用的设备(例如,iPhone 4s / 5 / 5s / 5c / 6/6 plus)使单元格适当地增加大小,从而无论使用哪种设备,始终每行显示3个项目/单元格用过的。
我从来没有能够做到这一点。 我在考虑手动设置尺寸,如下所示:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if DeviceHelper.DeviceType.IS_IPHONE_4_OR_LESS {
return CGSizeMake(115, 140)
} else if DeviceHelper.DeviceType.IS_IPHONE_5 {
return //size
} else if DeviceHelper.DeviceType.IS_IPHONE_6 {
return //size
} else {
return //size
}
}
我有一个帮助程序,可以确定正在使用的设备,可以在应用程序中的任何位置调用它。 但是,没有一种方法可以确保无论使用什么设备,每行都始终显示3个单元格,并且还显示相同的填充,如下所示:
宽高比限制很有帮助,但是这次我不能将它们应用于单元格,因为接口构建器不允许这样做。 有没有直接做到这一点?
在此先感谢您的时间。
删除默认的单元格间距:
试试这个代码:
只需为numberOfCellInRow
设置值即可收集一行视图中的单元格数
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
int numberOfCellInRow = 3;
CGFloat padding = 5.0;
CGFloat collectionCellWidth = [[UIScreen mainScreen] bounds].size.width/numberOfCellInRow;
CGFloat finalWidthWithPadding = collectionCellWidth - padding;
return CGSizeMake(finalWidthWithPadding , finalWidthWithPadding);
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var numberOfCellInRow : Int = 3
var padding : Int = 5
var collectionCellWidth : CGFloat = (self.view.frame.size.width/CGFloat(numberOfCellInRow)) - CGFloat(padding)
return CGSize(width: collectionCellWidth , height: collectionCellWidth)
}
我认为它将适用于所有设备。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.