Make a note of how to use CollectionView after TableView.
Add ID to Cell
1.2 DataSource, Delegate (on source code) Add protocol in ViewController
CellDetailPageViewController
class CellDetailPageViewController: UIViewController,UICollectionViewDelegate, UICollectionViewDataSource {
}
Add CollectionView instance
CellDetailPageViewController
@IBOutlet weak var collectionView: UICollectionView!
1.3 Add method as returned with error Determine the number of cells
CellDetailPageViewController
let contentNeedShow = ["Apple","Strawberry","grape","Pineapple","Kiwi","Tateyama","Mt. Nantai","Mt. Tanigawa","Mt. Kinpu","Hotakadake","Daibosatsu Mt.","coffee","Soy milk","juice","Carbonated","water"]
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return contentNeedShow.count
}
Determine the contents of the Cell (set the color of the basic element)
CellDetailPageViewController
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = UIColor.lightGray
return cell
}
Cell
class Cell: UICollectionViewCell{
@IBOutlet weak var label: UILabel!
}
Change the variable that returns the contents of Cell
CellDetailPageViewController
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Cell
cell.backgroundColor = UIColor.lightGray
cell.layer.cornerRadius = 10
cell.label.text = contentNeedShow[indexPath.row]
return cell
}
2.2 Adjust the spacing between cells
Added new protocol UICollectionViewDelegateFlowLayout
CellDetailPageViewController
class CellDetailPageViewController: UIViewController,UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
}
Add method
CellDetailPageViewController
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let horizontalSpace : CGFloat = 20
let cellSize : CGFloat = self.view.bounds.width / 3 - horizontalSpace
return CGSize(width: cellSize, height: cellSize)
}
Add to viewDidLoad
CellDetailPageViewController
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
collectionView.collectionViewLayout = layout
}
The result looks like this
Recommended Posts