//put the images in to project
import UIKit
2
3 class ViewController:UIViewController,
UICollectionViewDataSource, UICollectionViewDelegate {
4
5 var images = [“Pic1”, “Pic2”, “Pic3”, “Pic8”, “Pic5”,
“Pic6”, “Pic7”, “Pic4”, “Pic9”]
6
7 override func viewDidLoad() {
8 super.viewDidLoad()
9 // Do any additional setup after loading the view,
typically from a nib.
10 let screenRect = UIScreen.main.bounds
11 let rect = CGRect(x:0, y:20, width:
screenRect.size.width, height:screenRect.size.height - 20)
12
13 let flowLayout = UICollectionViewFlowLayout()
14 flowLayout.itemSize = CGSize(width:155, height:
15 flowLayout.scrollDirection =
UICollectionViewScrollDirection.vertical
16
17 let collectionView = UICollectionView(frame:rect,
collectionViewLayout:flowLayout)
18
19 collectionView.dataSource = self
20 collectionView.delegate = self
21
collectionView.register(UICollectionViewCell.classForCoder(),
forCellWithReuseIdentifier: “reusedCell”)
22 self.view.addSubview(collectionView)
23 }
24
25 func collectionView(_ collectionView:
UICollectionView, numberOfItemsInSection section:Int) ->
Int {
26 return images.count
27 }
28
29 func collectionView(_ collectionView:
UICollectionView, cellForItemAt indexPath:IndexPath) ->
UICollectionViewCell {
30
31 let identifier = “reusedCell”
32 let cell =
collectionView.dequeueReusableCell(withReuseIdentifier:
identifier, for:indexPath)
33
34 let imageView:UIImageView?= cell.viewWithTag(1)
as?UIImageView
35 if imageView == nil{
36 let image = UIImage(named:images[(indexPath as
NSIndexPath).row])
37 let imageView = UIImageView(image:image)
38 imageView.frame = CGRect(x:0, y:0, width:150,
height:135)
39 imageView.layer.opacity = 0.5
40 imageView.tag = 1
41 cell.addSubview(imageView)
42 }else{
43 imageView?.image = UIImage(named:
images[(indexPath as NSIndexPath).row])
44 }
45
46 return cell
47 }
48
49 func collectionView(_ collectionView:
UICollectionView, didSelectItemAt indexPath:IndexPath) {
50 let cell = collectionView.cellForItem(at:indexPath)
51 let imageView = cell?.viewWithTag(1)
52 imageView?.layer.opacity = 1.0;
53 }
54 }
image.png
//UICollectionView包括三个部分:Cells、Supplementary Views、Decoration Views
image.png
image.png
image.png
image.png