Created
May 30, 2019 23:00
-
-
Save standinga/726c31bd3ea866643d5d8520c3343ab3 to your computer and use it in GitHub Desktop.
CustomView.swift for medium post about UICollectionView inside UIView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
@IBDesignable | |
class CustomView: UIView { | |
@IBOutlet var contentView: UIView! | |
@IBOutlet weak var collectionView: UICollectionView! | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
commonInit() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
commonInit() | |
} | |
private func commonInit() { | |
let bundle = Bundle(for: type(of: self)) | |
bundle.loadNibNamed("CustomView", owner: self, options: nil) | |
addSubview(contentView) | |
contentView.frame = bounds | |
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
contentView.backgroundColor = .red | |
initCollectionView() | |
} | |
private func initCollectionView() { | |
let nib = UINib(nibName: "CustomCell", bundle: nil) | |
collectionView.register(nib, forCellWithReuseIdentifier: "CustomCell") | |
collectionView.dataSource = self | |
} | |
} | |
extension CustomView: UICollectionViewDataSource { | |
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { | |
return 20 | |
} | |
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { | |
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as? CustomCell else { | |
fatalError("can't dequeue CustomCell") | |
} | |
cell.label.text = "\(indexPath.item)" | |
return cell | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment