在collectionView的每行单元格上显示4张图像,可以通过以下步骤实现:
以下是一个示例代码:
import UIKit
class ImageCell: UICollectionViewCell {
let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
// 设置imageView的布局和样式
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.frame = contentView.bounds
contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let images = [UIImage(named: "image1"), UIImage(named: "image2"), UIImage(named: "image3"), UIImage(named: "image4"), UIImage(named: "image5"), UIImage(named: "image6")]
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
override func viewDidLoad() {
super.viewDidLoad()
// 设置collectionView的布局和样式
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(ImageCell.self, forCellWithReuseIdentifier: "ImageCell")
collectionView.backgroundColor = .white
view.addSubview(collectionView)
// 设置collectionView的约束
collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
// MARK: - UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
cell.imageView.image = images[indexPath.item]
return cell
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.bounds.width / 4 - 10 // 每行显示4张图像,减去间距
let height = width
return CGSize(width: width, height: height)
}
}
在上述示例代码中,我们创建了一个UICollectionView,并设置其布局为UICollectionViewFlowLayout。然后,我们创建了一个自定义的UICollectionViewCell子类ImageCell,用于显示图像。在ViewController中,我们实现了UICollectionViewDataSource和UICollectionViewDelegateFlowLayout协议中的方法,分别用于设置数据源和布局。在cellForItemAt方法中,我们根据indexPath获取对应的单元格,并设置图像。在sizeForItemAt方法中,我们设置每个单元格的大小。
这样,就可以在collectionView的每行单元格上显示4张图像了。你可以根据实际需求进行修改和优化。
领取专属 10元无门槛券
手把手带您无忧上云