Swift 如何在“行集合”视图中创建2个单元格
我正试着像截图一样在一行中获得两张图像 但这是我真正的结果 以下是我对ViewController的扩展:Swift 如何在“行集合”视图中创建2个单元格,swift,uicollectionview,Swift,Uicollectionview,我正试着像截图一样在一行中获得两张图像 但这是我真正的结果 以下是我对ViewController的扩展: extension ViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInS
extension ViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count // images is an array of my UIImages`s
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellImage", for: indexPath) as! imageCollectionViewCell
cell.imageView.image = images[indexPath.item]
cell.imageView.contentMode = .scaleAspectFill
cell.imageView.clipsToBounds = true
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let frameCV = collectionView.frame//размер collectionView
let cellWidth = frameCV.width / CGFloat(countOfCells) // countOfCells == 2
let cellHeight = cellWidth
return CGSize(width: cellWidth, height: cellHeight)
}
}
您需要添加填充
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
let leftAndRightPaddings: CGFloat = 45.0
let numberOfItemsPerRow: CGFloat = 2.0
let width = (collectionView.frame.width-leftAndRightPaddings)/numberOfItemsPerRow
return CGSize(width: width, height: width) // You can change width and height here as pr your requirement
}
}