以下是一个iOS仿微信图片分享界面的实现代码的示例:
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var collectionView: UICollectionView!
var images = [UIImage(named: "image1"), UIImage(named: "image2"), UIImage(named: "image3"), UIImage(named: "image4"), UIImage(named: "image5")]
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 100, height: 100)
layout.minimumInteritemSpacing = 10
layout.minimumLineSpacing = 10
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(ImageCell.self, forCellWithReuseIdentifier: "ImageCell")
collectionView.backgroundColor = .white
view.addSubview(collectionView)
}
// MARK: UICollectionViewDelegate, UICollectionViewDataSource
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: ImageCell
class ImageCell: UICollectionViewCell {
var imageView: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
imageView = UIImageView(frame: contentView.bounds)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
在上述示例代码中,我们创建了一个UICollectionView
来展示图片。我们使用了一个自定义的UICollectionViewCell
子类ImageCell
来展示图片。每个ImageCell
包含一个UIImageView
来显示图片。我们将图片添加到images
数组中,并在collectionView(_:cellForItemAt:)
方法中将其赋值给相应的ImageCell
。
注意,在上述示例代码中,我们使用了一些占位图片来展示,你需要将其替换为你自己的图片资源。