以下是一個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
。
注意,在上述示例代碼中,我們使用了一些占位圖片來展示,你需要將其替換為你自己的圖片資源。