How to make UICollectionView dynamic height? - ios

How to make UICollectionView dynamic height? The height of the UICollectionView should depend on the number of cells in it.
class ProduitViewController: UIViewController {
var productCollectionViewManager: ProductCollectionViewManager?
var sizeCollectionViewManager: SizeCollectionViewManager?
var product: ProductModel?
var selectedSize: String?
#IBOutlet weak var productCollectionView: UICollectionView!
#IBOutlet weak var sizeCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
}
private extension ProduitViewController {
func setup() {
guard let product = product else { return }
colorNameLabel.text = product.color[0].name
sizeCollectionViewManager = SizeCollectionViewManager.init()
sizeCollectionView.delegate = sizeCollectionViewManager
sizeCollectionView.dataSource = sizeCollectionViewManager
sizeCollectionViewManager?.set(product: product)
sizeCollectionViewManager?.didSelect = { selectedSize in
self.selectedSize = selectedSize
}
sizeCollectionView.reloadData()
}
}
Collection View Manager
import UIKit
final class SizeCollectionViewManager: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var sizeProduct: [SizeModel] = []
var didSelect: ((String) -> Void)?
func set(product: ProductModel) {
sizeProduct = product.size
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sizeProduct.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SizeCell", for: indexPath) as? SizeCollectionViewCell {
cell.configureCell(cellModel: sizeProduct[indexPath.row])
return cell
}
return UICollectionViewCell.init()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width / 3 + 20
let height: CGFloat = 35
return CGSize(width: width, height: height)
}
}
The height is now 35. If it is not set static, then the collection view will disappear altogether from the screen.
Screenshot Storyboard

You should set a height constraint on the UICollectionView reference. Once the constraint is set, you can calculate and set the constraint value based on number of objects, since you know how many rows it should display.

Related

CollectionView Cells not sizing properly

I have created a collection view with cells that are just meant to display an image and a title underneath. Everything appears right in the interface builder and with the constraints. When the view actually loads the whole image does not load and is cut off as you can see in the images below. What I would like is for the cells to size to an xth of the screen (let's say third of the screen width for simplicity) ?
NewsController
class NewsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
private static let headlineArticleReuseIdentifier = "HeadlineArticleCell"
private static let categoryCellReuseIdentifier = "NewsCategoryCell"
#IBOutlet weak var categoriesList: UICollectionView!
#IBOutlet weak var categoriesFlowLayout: UICollectionViewFlowLayout!
#IBOutlet weak var headlineArticlesPreviewList: UITableView!
private var bindings = Set<AnyCancellable>()
private var viewModel: NewsViewModel = NewsViewModel()
private var headlineArticles: [Article] = []
private var categories: [Category] = []
#IBOutlet weak var headlineTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.isSkeletonable = true
view.showGradientSkeleton()
headlineArticlesPreviewList.delegate = self
headlineArticlesPreviewList.dataSource = self
categoriesList.dataSource = self
categoriesList.delegate = self
let cancellable = viewModel.$viewState.sink(receiveValue: { state in
switch state {
case let .data(data):
self.setData(data: data)
print()
case let .error(error):
print(error)
case .loading:
self.headlineTitle.showGradientSkeleton()
self.headlineArticlesPreviewList.showGradientSkeleton()
print()
}
})
bindings.insert(cancellable)
}
private func setData(data: NewsViewModel.ViewState.Data) {
self.view.hideSkeleton()
self.headlineArticles = data.headlineArticles
self.headlineTitle.text = data.headlineCategory.displayName
self.headlineArticlesPreviewList.reloadData()
self.categories = data.categories
self.categoriesList.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (tableView == headlineArticlesPreviewList) {
return headlineArticles.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = headlineArticlesPreviewList.dequeueReusableCell(
withIdentifier: NewsViewController.headlineArticleReuseIdentifier,
for: indexPath)
as? HeadlineArticleTableViewCell else {
fatalError("could not cast to headline article")
}
let headlineArticle = headlineArticles[indexPath.item]
cell.setArticle(article: headlineArticle)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
self.categories.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = categoriesList.dequeueReusableCell(withReuseIdentifier: NewsViewController.categoryCellReuseIdentifier, for: indexPath) as? NewsCategoryCollectionViewCell else {
fatalError("could not cast to news category")
}
let newsCategory = categories[indexPath.item]
cell.setCategory(category: newsCategory)
cell.isInteractable = true
cell.cornerRadius = 8
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let noOfCellsInRow = 3
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(noOfCellsInRow - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(noOfCellsInRow))
return CGSize(width: size, height: size)
}
}
Constraints
Cell Image
Cell Size
What happens
Please add UICollectionViewDelegateFlowLayout to your code.
Swift
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: UIScreen.main.bounds.size.width * 0.4,height: UIScreen.main.bounds.size.width * 0.4)
}
objective c
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake([[UIScreen mainScreen] bounds].size.width * 0.4, [[UIScreen mainScreen] bounds].size.height * 0.4);
}
Is your collection view set to be self sizing? It looks like its using the default item sizes for the collection view. You can read more about how to implement a self sizing collectionView here
Another suggestion, if you are using fix aspect ratio: 1:1 and the imageView's width is 144, just set the height constraint as 144 also and remove the aspect ratio.
Third suggestion, look at the console, are there any LayoutConstraint errors? If so, it is likely that it cannot create the 1:1 aspect ratio and breaks a constraint. You can try lowering the aspect ratio's priority to 750, it usually helps in these situation, if not, look at the first two suggestions.
Also, I see that your label is also at a fixed height, 25, so technically, your cell is 144*(144+25) so you can set your itemSize to these values and don't use self sizing altogether.

Insert Item in UICollectionView dynamically

I'm working on a requirement where I need to add the items in a UICollectionView dynamically.
Here is my code of ViewController
import UIKit
class ViewController: UIViewController {
enum Direction {
case Horizonatal
case Verticle
}
var enumDirection: Direction = .Verticle
var direction = "Verticle"
var SectionsAndRows = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
SectionsAndRows.append(4)
SectionsAndRows.append(3)
SectionsAndRows.append(2)
SectionsAndRows.append(1)
//SectionsAndRows.append(5)
}
#IBOutlet var gridCollectionView: UICollectionView! {
didSet {
gridCollectionView.bounces = false
}
}
#IBOutlet var gridLayout: UICollectionViewFlowLayout! {
didSet {
//gridLayout.stickyRowsCount = 0
gridLayout.scrollDirection = .horizontal
//gridLayout.stickyColumnsCount = 0
gridLayout.minimumLineSpacing = 5
gridLayout.minimumInteritemSpacing = 5
}
}
}
// MARK: - Collection view data source and delegate methods
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return SectionsAndRows.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(SectionsAndRows[section])
return SectionsAndRows[section]
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.reuseID, for: indexPath) as? CollectionViewCell else {
return UICollectionViewCell()
}
print("Current Section ==\(indexPath.section) CurrentRow ===\(indexPath.row) and its rows count ==\(SectionsAndRows[indexPath.section])")
cell.titleLabel.text = ""
cell.btn.addTarget(self, action: #selector(handleAdd(sender:)), for: .touchUpInside)
cell.btn.tag = (indexPath.section * 1000) + indexPath.row
if enumDirection == .Verticle {
if indexPath.section == SectionsAndRows.count - 1 {
cell.btn.setTitle("+", for: .normal)
} else {
cell.btn.setTitle("\(indexPath)", for: .normal)
}
}
return cell
}
#objc func handleAdd(sender: UIButton) {
// Perform some opration
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
}
CollectionViewCell.swift
import UIKit
class CollectionViewCell: UICollectionViewCell {
static let reuseID = "CollectionViewCell"
#IBOutlet weak var btn: UIButton!
#IBOutlet weak var titleLabel: UILabel!
}
If you run the code, it will show a Collection of 1 row and 1 column in each row. If you uncomment the last line of viewDidLoad() (SectionsAndRows.append(5)) function, then it works fine.
My observation is that the last section of the CollectionView will have the highest number of a column. Is that correct or is this a bug of a CollectionView?

How can I dynamically set multiple buttons having different length of string according to screen's width?

(source: uimovement.com)
I want to implement layout like the above(auto line break when screen's width is not enough to accommodate buttons' widths).
But I can't come up with any idea about how to make that image like layout. I just can implement statically, not dynamically.
In Android, there is a layout that can implement the above.
But I don't know what can help me implement the above image in swift.
Please help me.
Following #Matthew Mitchell 's suggestion.
I implemented it like below.
My ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
var hobbyArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
// self.collectionView!.register(CollectionViewCell.self, forCellWithReuseIdentifier: "cell")
hobbyArray.append("test1")
hobbyArray.append("test2")
hobbyArray.append("test3")
hobbyArray.append("test4")
hobbyArray.append("test5")
hobbyArray.append("test5")
hobbyArray.append("test5123123")
collectionView.reloadData()
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return hobbyArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.title.text = self.hobbyArray[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let text = self.hobbyArray[indexPath.row]
let cellWidth = text.size(withAttributes:[.font: UIFont.systemFont(ofSize:17)]).width + 25
return CGSize(width: cellWidth, height: 35.0)
}
}
Other codes are implemented exactly equal to #Matthew Mitchell's codes.
However, still I can't get what I wanted to implement.
I failed to make what I had wanted.
To do this efficiently you need to have a UICollectionView with a custom FlowLayout. I am going to do a storyboard example. This is quite complicated so I will try my best. All the code will be below the steps.
Step 1: Create a swift file named CollectionViewFlowLayout and use UICollectionViewLayout code in the newly created class.
Step 2: Add a UICollectionView to your ViewController
Step 3: Link new UICollectionView layout with the CollectionViewFlowLayout class
Step 4: Create a UICollectionViewCell inside the UICollectionView, add a label to that cell and constrain it to left and right in the cell and center it vertically. In the attributes inspector of the cell give it a reusable identifier ("cell" for this example)
Step 6: Create a swift file named collectionViewCell and use UICollectionViewCell class that links to your collectionViewCell (same way you linked your flowlayout in step 3).
Step 7: Add ViewController code to your ViewController Class. This code allows you to add cells to your collection view. The sizeForItemAt function will allow you to resize the cells according to the width of the string that you put inside each cell.
Code:
ViewController:
import UIKit
class viewController: UIViewController {
//Outlets
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
collectionView.delegate = self
collectionView.dataSource = self
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return YOUR_ITEM_COUNT
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
self.title.text = YOUR_ITEMS_LIST[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let text = YOUR_ITEMS_LIST[indexPath.row]
let cellWidth = text!.size(withAttributes:[.font: UIFont.systemFont(ofSize:17)]).width + 25
return CGSize(width: cellWidth, height: 35.0)
}
}
UICollectionViewCell:
class CollectionViewCell: UICollectionViewCell {
//Outlets
#IBOutlet weak var title: UILabel!
}
UICollectionViewFlowLayout:
import UIKit
class CollectionViewFlowLayout: UICollectionViewFlowLayout {
var tempCellAttributesArray = [UICollectionViewLayoutAttributes]()
let leftEdgeInset: CGFloat = 0
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let cellAttributesArray = super.layoutAttributesForElements(in: rect)
//Oth position cellAttr is InConvience Emoji Cell, from 1st onwards info cells are there, thats why we start count from 2nd position.
if(cellAttributesArray != nil && cellAttributesArray!.count > 1) {
for i in 1..<(cellAttributesArray!.count) {
let prevLayoutAttributes: UICollectionViewLayoutAttributes = cellAttributesArray![i - 1]
let currentLayoutAttributes: UICollectionViewLayoutAttributes = cellAttributesArray![i]
let maximumSpacing: CGFloat = 8
let prevCellMaxX: CGFloat = prevLayoutAttributes.frame.maxX
//UIEdgeInset 30 from left
let collectionViewSectionWidth = self.collectionViewContentSize.width - leftEdgeInset
let currentCellExpectedMaxX = prevCellMaxX + maximumSpacing + (currentLayoutAttributes.frame.size.width )
if currentCellExpectedMaxX < collectionViewSectionWidth {
var frame: CGRect? = currentLayoutAttributes.frame
frame?.origin.x = prevCellMaxX + maximumSpacing
frame?.origin.y = prevLayoutAttributes.frame.origin.y
currentLayoutAttributes.frame = frame ?? CGRect.zero
} else {
// self.shiftCellsToCenter()
currentLayoutAttributes.frame.origin.x = leftEdgeInset
//To Avoid InConvience Emoji Cell
if (prevLayoutAttributes.frame.origin.x != 0) {
currentLayoutAttributes.frame.origin.y = prevLayoutAttributes.frame.origin.y + prevLayoutAttributes.frame.size.height + 08
}
}
}
}
return cellAttributesArray
}
func shiftCellsToCenter() {
if (tempCellAttributesArray.count == 0) {return}
let lastCellLayoutAttributes = self.tempCellAttributesArray[self.tempCellAttributesArray.count-1]
let lastCellMaxX: CGFloat = lastCellLayoutAttributes.frame.maxX
let collectionViewSectionWidth = self.collectionViewContentSize.width - leftEdgeInset
let xAxisDifference = collectionViewSectionWidth - lastCellMaxX
if xAxisDifference > 0 {
for each in self.tempCellAttributesArray{
each.frame.origin.x += xAxisDifference/2
}
}
}
}
You can use a UICollectionView with custom UICollectionViewFlowLayout or use a fully custom solution with UIView as root and different UIScrollViews with some custom content as lines (cells) here.
I have an example, but it's too huge to post here. Write me if you are inserting in.
I had the same problem and i found a shortest and super easy solution to make the height dynamic by subclassing UICollectionView and assign it to the CollectionView.
Here's the code:
class DynamicHeightCollectionView: UICollectionView {
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
override var intrinsicContentSize: CGSize {
return self.collectionViewLayout.collectionViewContentSize
}
}
I am attaching reference link to that solution.
https://stackoverflow.com/a/49297382/9738186

Scrolling issue with UITableViewController hosted in UICollectionViewCell

I have the following setup in my app:
UITabBarController
UINavigationController
UIViewController
The UIViewController has a UICollectionView with horizontal scrolling.
In the cells, I want to "host" a view from another ViewController. This works pretty well, but I have scrolling issues. The first UICollectionViewCell hosts a view that comes from a UITableViewController. I can scroll the UITableViewController but it does not really scroll to the end - it seems like the UITableViewController starts to bounce way too early.
When I used the UITableViewController as the Root View Controller, everything worked fine, so I don't think there is something wrong with this ViewController.
The height of the CollectionView is pretty small, I just wanted to show the "bouncing" behaviour.
Here is the code for the collectionView:
import Foundation
import UIKit
class FeedSplitViewController : UIViewController, Controllable
{
#IBOutlet weak var menuBar: MenuBar!
#IBOutlet weak var collectionView: UICollectionView!
private var currentIndex = 0
private var dragStart: CGFloat = 0.0
private var feedActivities: FeedViewController!
var controller: Controller!
override func viewDidLoad()
{
super.viewDidLoad()
self.initControls()
self.initMenuBar()
self.initCollectionView()
self.initActivitiesViewController()
}
fileprivate func initActivitiesViewController()
{
self.feedActivities = UIStoryboard.instantiate("Main", "feedActivities")
self.feedActivities.controller = self.controller
}
fileprivate func initControls()
{
self.navigationController?.navigationBar.setValue(false, forKey: "hidesShadow")
}
fileprivate func initMenuBar()
{
self.menuBar.showLine = true
self.menuBar.enlargeIndicator = true
self.menuBar.texts = [Resources.get("FEED_ACTIVITIES"), Resources.get("DASHBOARD")]
self.menuBar.selectionChanged =
{
index in
self.collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: UICollectionView.ScrollPosition.right, animated: true)
}
}
fileprivate func initCollectionView()
{
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
let menuBarFrame = self.menuBar.frame.origin
let collectionView = self.collectionView.frame.origin
Swift.print(menuBarFrame)
Swift.print(collectionView)
}
}
extension FeedSplitViewController : UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
if indexPath.item == 0, let feedActivities = self.feedActivities
{
cell.contentView.addSubview(feedActivities.view)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
{
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: self.view.bounds.width, height: self.view.bounds.height)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView)
{
self.dragStart = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
let oldIndex = self.currentIndex
let page = scrollView.contentOffset.x / scrollView.frame.size.width
let currentPage = Int(round(page))
if oldIndex != currentPage
{
if Settings.useHapticFeedback
{
Utilities.haptic(.medium)
}
self.menuBar.selectedIndex = currentPage
}
self.currentIndex = currentPage
}
}
I have attached a small video: https://imgur.com/a/pj7l3Hd
I solved it by doing the following:
I no longer host the view of an ViewController directly in the
Every UICollectionView cell hosts an UITableView.
The UITableViewCell contains the data model that was previously implemented in the ViewController. The logic is still outside of the UITableViewCell.

Get indexPath from UICollectionViewController to UICollectionViewCell subclass

in my view controller I Am loading a custom CollectionViewCell with subclass. Based on the position of a cell's indexpath I want to format the text labels differently. I.e. first row has only one cell with bigger text, whereas the second has two cell with smaller text.
How can I access the indexpath from my UICollectionView in my UICollectionViewCell subclass? I tried a delegate protocol but this always returns nil.
Code below and Thanks so much!
Markus
UICollectionViewController:
import UIKit
protocol WorkoutDataViewControllerCVDataSource: AnyObject {
func workoutType(for workoutDataViewControllerCV: WorkoutDataViewControllerCV) -> WorkoutType
func workoutDistance(for workoutDataViewControllerCV: WorkoutDataViewControllerCV) -> Double
func workoutDuration(for workoutDataViewControllerCV: WorkoutDataViewControllerCV) -> Double
func workoutInstantVelocity(for workoutDataViewControllerCV: WorkoutDataViewControllerCV) -> Double
}
final class WorkoutDataViewControllerCV: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
weak var dataSource: WorkoutDataViewControllerCVDataSource!
private lazy var velocityFormatter = VelocityFormatter(dataSource: self, delegate: self)
private lazy var averageVelocityFormatter = VelocityFormatter(dataSource: self, delegate: self)
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.register(MeasurementCollectionViewCell.preferredNib, forCellWithReuseIdentifier: MeasurementCollectionViewCell.preferredReuseIdentifier)
}
}
// MARK: - Managing UICollectionView
extension WorkoutDataViewControllerCV: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Measurement Cell", for: indexPath)
return cell
}
}
extension WorkoutDataViewControllerCV: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let availableWidth = self.view.frame.width
switch indexPath.row {
case 0: return CGSize(width: availableWidth, height: 150)
case 1: return CGSize(width: availableWidth/2.1, height: 150)
case 2: return CGSize(width: availableWidth/2.1, height: 150)
case 3: return CGSize(width: availableWidth, height: 150)
default:
return CGSize(width: availableWidth/2.1, height: 150)
}
}
}
// MARK: - Managing VelocityFormatter
extension WorkoutDataViewControllerCV: VelocityFormatterDataSource {
func duration(for velocityFormatter: VelocityFormatter) -> Double {
return dataSource.workoutDuration(for: self)
}
func distance(for velocityFormatter: VelocityFormatter) -> Double {
return dataSource.workoutDistance(for: self)
}
func instantVelocity(for velocityFormatter: VelocityFormatter) -> Double {
return dataSource.workoutInstantVelocity(for: self)
}
}
UICollectionViewCell.swift
import UIKit
final class MeasurementCollectionViewCell: UICollectionViewCell {
#IBOutlet private var measurementPropertyLabel: UILabel!
#IBOutlet private var measurementValueLabel: UILabel!
#IBOutlet private var measurementUnitLabel: UILabel!
static let preferredReuseIdentifier = "Measurement Cell"
static let preferredNib = UINib(nibName: "MeasurementCollectionViewCell", bundle: nil)
override func awakeFromNib() {
super.awakeFromNib()
updateMeasurement(property: "Speed", value: "100", unit: "km/h")
//measurementValueLabel.font = measurementValueLabel.font.monospacedDigitFont
}
func updateMeasurement(property: String, value: String, unit: String?) {
measurementPropertyLabel.text = property
measurementValueLabel.text = value
measurementUnitLabel.text = unit
}
}
Get the instance of cell in UICollectionView delegate method collectionView(_, didSelectItemAt _).
extension WorkoutDataViewControllerCV: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? MeasurementCollectionViewCell {
cell.selectedIndexPath(indexPath)
}
}
}
The indexPath will be passed as an argument in method selectedIndexPath to MeasurementCollectionViewCell from above method.
class MeasurementCollectionViewCell: UICollectionViewCell {
......
func selectedIndexPath(_ indexPath: IndexPath) {
//Do your business here.
}
}
You can use the responder chain to get the collection view of a cell with which you can get the index path. Just add these extensions in a new file called UICollectionViewCell+IndexPath.swift.
extension UIResponder {
func next<T: UIResponder>(_ type: T.Type) -> T? {
return next as? T ?? next?.next(type)
}
}
extension UICollectionViewCell {
var indexPath: IndexPath? {
return next(UICollectionView.self)?.indexPath(for: self)
}
}
Now inside your cell, you can use self.indexPath
Pretty straight forward way would be storing the indexPath into the subclass of UICollectionViewCell class. Assign it while returning from cellForRow at: index path. So now the subclassed collectionviewcell has access to the indexpath of it's own

Resources