我必须创建一个集合视图,这样无论iphone大小如何,我们每行只有2个图像,并且我们还需要每个行和列之间的边框,如图所示。
我想这样:
答案 0 :(得分:3)
试试这段代码。只是一种不同的方法。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets(top: 6, left: 4, bottom: 6, right: 4)
layout.minimumInteritemSpacing = 04
layout.minimumLineSpacing = 04
layout.invalidateLayout()
return CGSize(width: ((self.view.frame.width/2) - 6), height: ((self.view.frame.width / 2) - 6))
}
从不同设备上的代码输出。
答案 1 :(得分:2)
从collectionView的协议实现以下功能:
// cell size
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: view.frame.size.width/2, height: view.frame.size.width/2)
}
...其中view是您的控制器(超级)视图
// inter-spacing
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 2.0
}
func collectionView(collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 2.0
}
答案 2 :(得分:1)
Swift 4. *和Xcode 9.3
如果您在同一ViewController上使用多个collectionView,则可以使用以下内容-
// Height and Width for the cell
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
if collectionView.tag == 101 {
return CGSize(width: 60, height: 60)
}
else if collectionView.tag == 102 {
return CGSize(width: view.frame.size.width/2, height: view.frame.size.width/2)
}
else {
return CGSize(width: 50, height: 50)
}
}
// InterItemSpacing
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
if collectionView.tag == 101 {
return 5.0
}
else if collectionView.tag == 102 {
return 0.0
}
else {
return 5.0
}
}
// InterLineSpacing
func collectionView(_ collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
if collectionView.tag == 101 {
return 5.0
}
else if collectionView.tag == 102 {
return 0.0
}
else {
return 5.0
}
}