Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save konnnn/b8e0aa966277770bef26055b1edaa702 to your computer and use it in GitHub Desktop.
Save konnnn/b8e0aa966277770bef26055b1edaa702 to your computer and use it in GitHub Desktop.
Adding UICollectionView with Custom Cell to UIViewController programmatically
// Created by Evgeny Konkin on 17.06.2019.
class ViewController: UIViewController {
var collectionView: UICollectionView!
// MARK: - Views Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
}
// MARK: - Setup Views
func setupCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: view.frame.width, height: 300)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .white
collectionView.showsVerticalScrollIndicator = false
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: CustomCell.identifier)
self.view.addSubview(collectionView)
}
}
// MARK: - CollectionView DataSource Methods
extension WeatherViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomCell.identifier, for: indexPath) as! CustomCell
return cell
}
}
// MARK: - Custom Cell Class
class CustomCell: UICollectionViewCell {
static let identifier = "CustomCell"
let label: UILabel = {
let label = UILabel()
label.text = "Custom Cell"
label.textColor = .white
label.backgroundColor = .blue
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .blue
self.addSubview(label)
label.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16).isActive = true
label.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 16).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
@bhagyashriparab
Copy link

how to get onclick on label

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment