简体   繁体   English

自适应UICollectionView单元格宽度

[英]Adaptive UICollectionView Cell Width

I am new to collection view and Auto Layout and I have a problem making the cell sizes adapt to the various devices in the simulator. 我是集合视图和自动版式的新手,在使像元大小适应模拟器中的各种设备时遇到问题。 I am using the flow-layout and I set the sizes in the size inspector. 我正在使用流程布局,并在尺寸检查器中设置了尺寸。 The image I've provided shows the way I need the cells to look(canvas on the left iPhone5)on all devices. 我提供的图像显示了我需要这些单元格在所有设备上看起来的方式(左侧iPhone5上的画布)。 The iPhone4 display is good but the 6s is incorrect. iPhone4的显示效果不错,但6s不正确。 Can someone please show me how this is done as I cannot find the precise information I am looking for. 有人可以告诉我如何执行此操作,因为我找不到所需的确切信息。 Thanks 谢谢

Also, I'm not sure why the iPhone5 doesn't display the cells on the preview section like the 4&6 do..? 另外,我不确定为什么iPhone5不会像4&6那样在预览部分显示单元格。 any clues..? 任何线索..?

screen shot1 屏幕截图1

With UICollectionView , you need to calculate the size of your cells, and the space around them (insets and interitem spacing) using delegate methods. 使用UICollectionView ,您需要使用委托方法来计算单元格的大小以及它们周围的空间(插入和项目间距)。

Something like this should work for you: 这样的事情应该为您工作:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

    return UIEdgeInsets(top: 8, left: 4, bottom: 0, right: 4)
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
    return CGFloat(8)
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let cellWidth = (view.bounds.size.width - 16) / 2
    let cellHeight = cellWidth * 0.8 // multiply by some factor to make cell rectangular not square

    return CGSize(width: cellWidth, height: cellHeight)
}

Within a UICollectionViewCell is where you would use Auto Layout to position the things in the cell, like labels, images, etc. UICollectionViewCell中,您可以使用“自动布局”在单元格中放置事物,例如标签,图像等。

iPhone 5S

iPhone 6s Plus

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM